我有一个包含对象和数组的嵌套数据结构。如何提取信息,即访问特定或多个值(或键)?
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
如何访问
name
中第二项的items
?
最佳答案
初赛
JavaScript只有一种可以包含多个值的数据类型:对象。数组是对象的一种特殊形式。
(普通)对象具有以下形式
{key: value, key: value, ...}
数组具有以下形式
[value, value, ...]
数组和对象都公开
key -> value
结构。数组中的键必须是数字,而任何字符串都可以用作对象中的键。键值对也称为“属性”。可以使用点表示法来访问属性
const value = obj.someProperty;
或括号表示法,如果属性名称不是有效的JavaScript identifier name [spec],或者名称是变量的值:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
因此,只能使用方括号表示法访问数组元素:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
等等... JSON呢?
JSON是数据的文本表示形式,就像XML,YAML,CSV和其他形式一样。要使用此类数据,首先必须将其转换为JavaScript数据类型,即数组和对象(以及如何使用它们进行了说明)。问题Parse JSON in JavaScript?中说明了如何解析JSON。
进一步阅读材料
如何访问数组和对象是JavaScript的基本知识,因此建议阅读MDN JavaScript Guide,尤其是本节
Working with Objects
Arrays
Eloquent JavaScript - Data Structures
访问嵌套数据结构
嵌套数据结构是引用其他数组或对象的数组或对象,即其值是数组或对象。可以通过连续应用点或括号符号来访问此类结构。
这是一个例子:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
假设我们要访问第二项的
name
。这是我们逐步执行的方法:
如我们所见,
data
是一个对象,因此我们可以使用点表示法访问其属性。 items
属性的访问方式如下:data.items
该值是一个数组,要访问其第二个元素,我们必须使用括号表示法:
data.items[1]
该值是一个对象,我们再次使用点符号来访问
name
属性。因此,我们最终得到:const item_name = data.items[1].name;
另外,我们可以对任何属性使用括号符号,特别是如果名称包含使点符号用法无效的字符时:
const item_name = data['items'][1]['name'];
我正在尝试访问属性,但只返回
undefined
吗?在大多数情况下,当您获取
undefined
时,对象/数组根本没有具有该名称的属性。const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
使用
console.log
或console.dir
并检查对象/数组的结构。您尝试访问的属性可能实际上是在嵌套对象/数组上定义的。console.log(foo.bar.baz); // 42
如果属性名称是动态的,但我事先不知道该怎么办?
如果属性名称未知,或者我们要访问数组的对象/元素的所有属性,则可以对对象使用
for...in
[MDN]循环,对数组使用for
[MDN]循环来遍历所有属性/元素。对象
要遍历
data
的所有属性,我们可以遍历对象,如下所示: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
}
根据对象的来源(以及您要执行的操作),您可能必须在每次迭代中测试该属性是否确实是该对象的属性,还是它是继承的属性。您可以使用
Object#hasOwnProperty
[MDN]进行此操作。作为
for...in
和hasOwnProperty
的替代方法,可以使用Object.keys
[MDN]获取属性名称数组:Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
数组
要遍历
data.items
数组的所有元素,我们使用for
循环:for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
也可以使用
for...in
遍历数组,但是有一些原因应避免这样做:Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?。随着对ECMAScript 5的浏览器支持的增加,数组方法
forEach
[MDN]也成为有趣的替代方法:data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
在支持ES2015(ES6)的环境中,您还可以使用
for...of
[MDN]循环,该循环不仅适用于数组,而且适用于任何iterable:for (const item of data.items) {
// `item` is the array element, **not** the index
}
在每次迭代中,
for...of
直接为我们提供可迭代的下一个元素,没有“索引”可供访问或使用。如果我不知道数据结构的“深度”怎么办?
除了未知键外,数据结构的“深度”(即有多少个嵌套对象)也可能是未知的。如何访问深层嵌套的属性通常取决于确切的数据结构。
但是如果数据结构包含重复模式,例如对于二叉树的表示,解决方案通常包括recursively [Wikipedia]访问数据结构的每个级别。
这是获取二叉树的第一个叶子节点的示例:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
访问具有未知键和深度的嵌套数据结构的一种更通用的方法是测试值的类型并采取相应的措施。
这是一个将嵌套数据结构内的所有原始值添加到数组中的示例(假设它不包含任何函数)。如果遇到一个对象(或数组),我们只需对该值再次调用
toArray
(递归调用)。function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
帮手
由于复杂对象或数组的结构不一定很明显,因此我们可以检查每个步骤的值来决定如何进一步移动。
console.log
[MDN]和console.dir
[MDN]帮助我们做到这一点。例如(Chrome控制台的输出):> console.log(data.items)
[ Object, Object ]
在这里,我们看到
data.items
是一个包含两个都是对象的元素的数组。在Chrome控制台中,对象甚至可以立即展开和检查。> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
这告诉我们
data.items[1]
是一个对象,展开后,我们看到它具有三个属性,分别为id
,name
和__proto__
。后者是用于对象原型链的内部属性。但是,原型链和继承超出了此答案的范围。
关于javascript - 如何访问和处理嵌套对象,数组或JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560501/