Home » Jquery » javascript – Get Value from JSON for a given Key where parent key names are dynamic

javascript – Get Value from JSON for a given Key where parent key names are dynamic

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a json string which starts like this:

{ "0" : 
{"Jquery77768" : 
    {"nodeData": 
        {"id":32, "name": "Bob"}
        ----

I need to get the value which is there in the id key.
I tried to do something like this:

var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;

but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.

How can I get the value of the id field?

How to&Answer:

Since you mentioned dynamic key names (Jquery77768), It will be better to get the Object.values. (Assuming one key as in data).

var myID = Object.values(obj["0"])[0].nodeData.id;

Answer:

What about a general function ? But suppose order of keys may not be same everywhere…

var obj = '{ "0" : {"Jquery77768" : {"nodeData": {"id":32, "name": "Bob"} }}}';
obj = JSON.parse(obj);
console.log(goDownNth(obj[0], 1).nodeData.id);
console.log(goDownNth(obj[0], 1).nodeData.id === goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 1));
console.log(goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 2));

function goDownNth (obj, n) {
    for (var a in obj) {
        if (!--n) return obj[a];
    }
}