我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
我如何访问项目中的第二个项目的名称?
我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
我如何访问项目中的第二个项目的名称?
当前回答
这个问题很老了,所以作为当代的更新。随着ES2015的开始,有了其他方法来获取你需要的数据。现在有一个被称为对象解构的特性,用于访问嵌套对象。
Const data = { 42岁的代码: 项目:[{ id: 1、 名称:“foo” }, { id: 2 名称:“酒吧” }) }; const { 项目:[,{ 名称:secondName }) } =数据; console.log (secondName);
上面的例子从名为items的数组的name键创建了一个名为secondName的变量,该数组表示跳过数组中的第一个对象。
值得注意的是,对于这个例子来说,它可能有点过头了,因为简单的数组访问更容易阅读,但在一般情况下,它在分解对象时很有用。
这是对您的特定用例的非常简短的介绍,解构可能是一种不寻常的语法,首先要习惯。我建议阅读Mozilla的解构赋值文档来了解更多信息。
其他回答
我更喜欢JQuery。它更干净,更容易阅读。
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
如果你正在寻找一个或多个符合特定条件的对象,你可以使用query-js进行一些选择
//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});
还有一个single和一个singleOrDefault,它们的工作类似于firstand firstordefault。唯一的区别是,如果找到了不止一根火柴,他们就会扔。
关于query-js的进一步解释可以从这篇文章开始
以防万一,有人在2017年或以后访问这个问题,并寻找一种容易记住的方法,这里有一篇关于在JavaScript中访问嵌套对象而不被迷惑的详细博客文章
无法读取未定义错误的属性“foo”
1. Oliver Steele的嵌套对象访问模式
最简单、最干净的方法是使用Oliver Steele的嵌套对象访问模式
const name = ((user || {}).personalInfo || {}).name;
用这个符号,你永远不会碰到
无法读取未定义的属性“名称”。
你基本上检查user是否存在,如果不存在,你立即创建一个空对象。这样,下一层键将始终从一个存在的对象或空对象访问,而不会从undefined访问。
2. 使用数组缩减访问嵌套对象
为了能够访问嵌套数组,您可以编写自己的数组reduce util。
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// this will return the city from the first address item.
还有一种出色的类型处理最小库类型可以为您完成所有这些。
使用lodash是一个很好的解决方案
例:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
解释很简单:
Var数据= { 42岁的代码: 项目:[{ id: 1、 名称:“foo” }, { id: 2 名称:“酒吧” }) }; /* 1. “data”对象包含“items”对象*/ console.log(数据); /* 2. ' items '对象包含两个对象作为元素的数组*/ console.log (data.items); /* 3.你需要数组的第二个元素-从'[0,1]' */中的' 1 ' console.log (data.items [1]); /* 4. 你需要第二个对象的' name '属性的值-数组的元素)*/ console.log (data.items [1] . name);