通过名称访问JSON子级别 [英] Access JSON sub levels by name
问题描述
我有以下示例JSON
I have the following example JSON
var data = {
"menu": [
{
"name": "Event A",
"sub": [{
"name": "Sub Event A 1",
"sub": null
},
{
"name": "Sub Event A 2",
"sub": [{
"name": "Sub Sub Event A 2",
"sub": null
}]
}
]
},
{
"name": "Event B",
"sub": [{
"name": "Sub Event B 1",
"sub": null
},
{
"name": "Sub Event B 2",
"sub": [{
"name": "Sub Sub Event B 2",
"sub": null
}]
}
]
}
]
}
创建菜单时,我可以轻松地选择使用Event A
还是Event B
作为源,如下所示:
When I'm creating a menu I can easily choose whether to use Event A
or Event B
as the source as follows:
$(data.menu[0].sub).each(function(){ /* menu[0] therefore first, Event A */
$menu1.append(
getMenuItem1(this)
);
});
问题
是否可以通过name
字段的值进行选择?
Is it possible to select this by the value of the name
field?
类似的东西:$(data.menu[name="Event A"].sub)
推荐答案
是否可以通过
name
字段的值进行选择?
Is it possible to select this by the value of the
name
field?
是的,使用Array#find
(如果您只想要第一个)或Array#filter
(如果您想要所有匹配的).
Yes, using either Array#find
(if you just want the first one) or Array#filter
(if you want all matching ones).
Array#find
( ES2015 +,但可以填充):
Array#find
(ES2015+, but can be shimmed):
var firstMatchingItem = data.menu.find(function(entry) {
return entry.name == "Event A";
});
Array#filter
( ES5 +,但可以填充):
Array#filter
(ES5+, but can be shimmed):
var matchingItems = data.menu.filter(function(entry) {
return entry.name == "Event A";
});
使用ES2015的箭头功能,它们看上去都更加简单:
They both look simpler with ES2015's arrow functions:
var firstMatchingItem = data.menu.find(entry => entry.name == "Event A");
var matchingItems = data.menu.filter(entry => entry.name == "Event A");
这篇关于通过名称访问JSON子级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!