我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?
例如:
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'
}]
};
我如何访问项目中的第二个项目的名称?
当前回答
如果你正在寻找一个或多个符合特定条件的对象,你可以使用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的进一步解释可以从这篇文章开始
其他回答
你可以使用lodash _get函数:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
以防万一,有人在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.
还有一种出色的类型处理最小库类型可以为您完成所有这些。
python式、递归式和函数式方法来分解任意JSON树:
handlers = {
list: iterate,
dict: delve,
str: emit_li,
float: emit_li,
}
def emit_li(stuff, strong=False):
emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
print(emission % stuff)
def iterate(a_list):
print('<ul>')
map(unravel, a_list)
print('</ul>')
def delve(a_dict):
print('<ul>')
for key, value in a_dict.items():
emit_li(key, strong=True)
unravel(value)
print('</ul>')
def unravel(structure):
h = handlers[type(structure)]
return h(structure)
unravel(data)
其中data是python列表(从JSON文本字符串解析而来):
data = [
{'data': {'customKey1': 'customValue1',
'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
'viewport': {'northeast': {'lat': 37.4508789,
'lng': -122.0446721},
'southwest': {'lat': 37.3567599,
'lng': -122.1178619}}},
'name': 'Mountain View',
'scope': 'GOOGLE',
'types': ['locality', 'political']}
]
jQuery的grep函数允许你过滤数组:
var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; $.grep(data.items, function(item) { if (item.id === 2) { console.log(item.id); //console id of item console.log(item.name); //console name of item console.log(item); //console item object return item; //returns item object } }); // Object {id: 2, name: "bar"} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
//parent.subParent.subsubParent["almost there"]["final property"]
基本上,在它下面展开的每个后代之间使用一个点,当你有由两个字符串组成的对象名称时,你必须使用["obj Name"]符号。否则,只要一个点就足够了;
来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
在此基础上,访问嵌套数组将如下所示:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
另一份描述上述情况的更有用的文件: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
通过点走访问属性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation