Q: Find specific key in a given object in JS Find specific key in a given object including nested objects and nested arrays of objects. what could be best solution or technic in javascript?
Given key: reference
Given Object:
{
  "reference": "Patient/1",
  "subjectOrAnyKey": {
    "reference": "Patient/2"
  },
  "containedOrAnyKey": [
    {
      "reference": "Practitioner/4"
    },
    {
      "subjectOrAnyKey": {
        "reference": "Patient/11"
      },
      "requesterOrAnyKey": {
        "reference": "Practitioner/3"
      },
      "performerOrAnyKey": [
        {
          "reference": "Practitioner/4"
        }
      ]
    }
  ]
}

PS: Solved using the following:
    function findAllValues(obj, key){
        for (let [k, v] of Object.entries(obj)){
            if (k === key) {
                console.log(v)
            } else if (v.constructor === Array && !v.length === false){
                for (let entry of v){
                    findAllValues(entry, key)
                }
            } else if (v.constructor === Object && !Object.keys(v).length === false) {
                findAllValues(v, key)
            }
        }
    }


A: Recursion comes in handy in these types of objects, where you can't determine how nested they can be
please find the below snippet
a function that loops through every key inside an object, if the key matches and it's type is not an object, it prints its value. if it's an object, it calls the method itself with the nested object.
function findAllKeys(obj, key){
    for(let prop in obj){
        if(typeof obj[prop] !== 'object' && prop === key)
            console.log(obj[prop]);
        else if(typeof obj[prop] === 'object')
            findAllKeys(obj[prop],key)
    }
}

