Search code examples
javascriptlodash

How to find JSON nested object


I want to find the key:value if exists somewhere nested. My JSON looks like this

{
  "key1": {
    "key11": "foo11",
    "key12": "foo12",
    "key13": [
      "aaa",
      "bbb"
    ]
  },
  "key2": {
    "city": "New York",
    "state": "NY",
    "phone": [
      "20111",
      "20333"
    ]
  }
}

I need to find first occurrence e.g. "phone" key and get it's data. How to do it by using e.g. lodash rather than for/forEach. The key "phone" may or may not exist and not in first level primary object.. So I need first occurrence


Solution

  • You can achieve that using recursion.

    let obj = { "key1": { "key11": "foo11", "key12": "foo12", "key13": [ "aaa", "bbb" ] }, "key2": { "city": "New York", "state": "NY", "phone": [ "20111", "20333" ] } }
    
    
    function nestedKey(obj,key){
      if(obj[key]) return obj[key]
      for(let k in obj){
        if(typeof obj[k] === "object"){
          let temp = nestedKey(obj[k],key);
          if(temp) return temp;
        }
      }
    }
    
    console.log(nestedKey(obj,"phone"))
    console.log(nestedKey(obj,"phonee"))