I have a nested data structure containing objects and arrays. How to extract information, i.e. access specific or multiple values (or keys)?
For example:
var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
How to access thenameof the second item initems?
You can access it this way
or
Both methods are equal.
Preliminary knowledge
JavaScript has only one data type that can contain multiple values:Object.Arrayis a special form of object.
(Normal) objects have the following form
{key: value, key: value, ...}The form of the array is
Both arrays and objects expose a
key -> valuestructure. Keys in arrays must be numbers, while any string can be used as a key in an object. Key-value pairs are also called"properties".You can usedot notationto access properties
orBracket notation, if the property name is not a valid JavaScriptIdentifier name[spec], or the name Is the value of the variable:
Therefore, array elements can only be accessed using bracket notation:
Wait...what about JSON?
JSON is a text representation of data, just like XML, YAML, CSV, etc. To process such data, you first have to convert it to JavaScript data types, namely arrays and objects (how to process these data was just explained). QuestionParsing JSON in JavaScript? How to parse JSON is explained in.
Further reading material
How to access arrays and objects is JavaScript basic knowledge, so it is recommended to read theMDN JavaScript Guide, especially the various parts
Access nested data structures
A nested data structure is an array or object that refers to other arrays or objects, that is, its value is an array or object. Such structures can be accessed by successive application of dot or bracket notation.
This is an example:
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };Suppose we want to access the
nameof the second project.Here's how we do it step by step:
As we can see,
datais an object, so we can access its properties using dot notation.itemsThe attributes are accessed as follows:The value is an array, to access its second element we must use bracket notation:
The value is an object, and we again use dot notation to access the
nameproperty. So we end up with:Alternatively, we can use bracket notation for any attribute, especially if the name contains characters that make it invalid for dot notation:
I'm trying to access a property but I only get
undefinedmessages?Most of the time when you encounter
undefinedthe object/array simply does not have a property with that name.const foo = {bar: {baz: 42}}; console.log(foo.baz); // undefinedUse
console.logorconsole.dirand check the structure of the object/array. It's possible that the property you're trying to access is actually defined on a nested object/array.What if the property names are dynamic and I don't know them beforehand?
If the property name is unknown or we want to access all properties of the object/array element, we can use
for...in[MDN]Loop over objects andfor[MDN]Loop through arrays to iterate over all properties/elements.Object
To iterate over all properties of
data, we can iterate overobjectsas follows:for (const prop in data) { // `prop` contains the name of each property, i.e. `'code'` or `'items'` // consequently, `data[prop]` refers to the value of each property, i.e. // either `42` or the array }Depending on where the object comes from (and what you want to do), you may have to test on each iteration whether the property is indeed a property of the object, or an inherited property. You can use
Object#hasOwnProperty代码>[MDN].As an alternative to
for...inandhasOwnProperty, you can useObject.keys[MDN ]Getattribute name array:Object.keys(data).forEach(function(prop) { // `prop` is the property name // `data[prop]` is the property value });Array
To iterate over all elements of
data.itemsarraywe use aforloop: