I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
The Underscore js Way
Which is a JavaScript library that provides a whole mess of useful
functional programming
helpers without extending any built-in objects.Solution:
or
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
Another more useful document depicting the situation above: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
My
stringjson
is coming from PHP file but still, I indicate here invar
. When i directly take my json intoobj
it will nothing show thats why i put my json file asvar obj=JSON.parse(stringjson);
so after that i getmessage
obj and show in alert box then I getdata
which is json array and store in one varibleArrObj
then i read first object of that array with key value like thisArrObj[0].id
Here is dynamic approach - your 'deep' key is string
'items[1].name'
(you can use array notation[i]
at any level) - if key is invalid then undefined is return.