1

How to access nested child object in JSON-format using javascript considering I don't know how deep the child element is?

I have tried:

var body = json..simplyChild; 

but doesn't work for me

var json = {
    "root": {
        "firstChild": {
            "secondChild": {
                "simplyChild": "kek"
            }
        }
    }
}
wlh
  • 3,426
  • 1
  • 16
  • 32
Poklakni
  • 193
  • 2
  • 10
  • That's not [JSON](http://json.org) -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jan 29 '19 at 19:10
  • 1
    Are you asking how to find a given `value` of a particular `key` within a nested `Object` by means of a `function`? – wlh Jan 29 '19 at 19:13
  • You will want to use a recursive function that will loop over all the keys. if the value is an object call the method on that object. if it is equal to the key return the value of that key. – Get Off My Lawn Jan 29 '19 at 19:15

2 Answers2

1

Idealy you would just get the element normally. But this could should do what you want it to.

var json = 
{
    "root": {
        "firstChild": {
            "secondChild": {
                "simplyChild": "kek"
            }
        }
    }
}

function getNestedElement(obj, k){
    let keys = Object.keys(obj);
    for(let i = 0; i < keys.length; i++){
        let key = keys[i];
        if(key == k){
            return obj[key];
        }else{
            return getNestedElement(obj[key], k);
        }
    }
}
Shimmy568
  • 503
  • 2
  • 8
0

Use a recursive function that calls itself based on if the value is an object or not.

Here are two usage examples:

var json = {
  "root": {
    "firstChild": {
      "secondChild": {
        "simplyChild": "kek"
      },
      "little": "I am little"
    }
  }
}

function Find(key, obj) {
  for (let k in obj) {
    if (k == key) return obj[k]
    if (typeof obj[k] == 'object') { 
      let r = Find(key, obj[k]) 
      if (r) return r
    }
  }
}

console.log(Find('simplyChild', json))
console.log(Find('secondChild', json))
console.log(Find('little', json))
console.log(Find('unSetKey', json))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338