1

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

John Glabb
  • 1,336
  • 5
  • 22
  • 52

1 Answers1

0

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"))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73