📌  相关文章
📜  如何在javascript代码示例中访问对象数组

📅  最后修改于: 2022-03-11 15:02:17.040000             🧑  作者: Mango

代码示例4
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:

const data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};
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. The items property is accessed as follows:

data.items
The value is an array, to access its second element, we have to use bracket notation:

data.items[1]
This value is an object and we use dot notation again to access the name property. So we eventually get:

const item_name = data.items[1].name;
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:

const item_name = data['items'][1]['name'];