0

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?

Bluemarble
  • 1,925
  • 4
  • 20
  • 35
  • Your code appears to work fine: https://jsfiddle.net/RoryMcCrossan/hxbk6o4L/ – Rory McCrossan Feb 18 '20 at 10:59
  • 1
    you can use [] operator to access "Jquery77768" element: ```obj[0]["Jquery77768"].nodeData.id```, so you can put Jquery77768 dynamically – Aisultan Feb 18 '20 at 11:01
  • @RoryMcCrossan — It stops working when the property name `Jquery77768` changes (as the question says it does). – Quentin Feb 18 '20 at 11:01
  • 1
    @user2244399 - They can, and they can use dot notation as they are using already, but **that doesn't help** because they don't know what the value should be. – Quentin Feb 18 '20 at 11:02
  • 1
    So the question then becomes how do they determine what that key *should* be? Accessing the object is trivial after that. @Quentin the reason I posted my original comment was because the OP states that the code doesn't work as-is. The dynamic property name was an addendum to that. – Rory McCrossan Feb 18 '20 at 11:02
  • Yes the property name changes dynamically and it will not be known in advance. – Bluemarble Feb 18 '20 at 11:10

2 Answers2

1

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;
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • 1
    A lump of code completely free of any explanation as to how it solves the problem isn't very helpful. – Quentin Feb 18 '20 at 11:02
0

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];
    }
}
Jan
  • 2,178
  • 3
  • 14
  • 26