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
?
Best Answer
Preliminaries
JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.
(Plain) Objects have the form
Arrays have the form
Both arrays and objects expose a
key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".Properties can be accessed either using dot notation
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
For that reason, array elements can only be accessed using bracket notation:
Wait... what about JSON?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .
Further reading material
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
Let's assume we want to access the
name
of the second item.Here is how we can do it step-by-step:
As we can see
data
is an object, hence we can access its properties using dot notation. Theitems
property is accessed as follows:The value is an array, to access its second element, we have to use bracket notation:
This value is an object and we use dot notation again to access the
name
property. So we eventually get:Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
I'm trying to access a property but I get only
undefined
back?Most of the time when you are getting
undefined
, the object/array simply doesn't have a property with that name.Use
console.log
orconsole.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.What if the property names are dynamic and I don't know them beforehand?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the
for...in
[MDN] loop for objects and thefor
[MDN] loop for arrays to iterate over all properties / elements.Objects
To iterate over all properties of
data
, we can iterate over the object like so:Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with
Object#hasOwnProperty
[MDN].As alternative to
for...in
withhasOwnProperty
, you can useObject.keys
[MDN] to get an array of property names:Arrays
To iterate over all elements of the
data.items
array, we use afor
loop:One could also use
for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.With the increasing browser support of ECMAScript 5, the array method
forEach
[MDN] becomes an interesting alternative as well:In environments supporting ES2015 (ES6), you can also use the
for...of
[MDN] loop, which not only works for arrays, but for any iterable:In each iteration,
for...of
directly gives us the next element of the iterable, there is no "index" to access or use.What if the "depth" of the data structure is unknown to me?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.
Here is an example to get the first leaf node of a binary tree:
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call
toArray
again on that value (recursive call).Helpers
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further.
console.log
[MDN] andconsole.dir
[MDN] help us doing this. For example (output of the Chrome console):Here we see that that
data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.This tells us that
data.items[1]
is an object, and after expanding it we see that it has three properties,id
,name
and__proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.