我有两个包含JSON对象的数组:x
和y
。我想创建一个新数组newSet
,其中包含来自x
的所有serverId
包含在y
中的对象。我还需要遍历x。
var x = [
{
"name": "Menu",
"serverId": "MENU",
"children": []
},
{
"name": "Dashboard",
"serverId": "DASHBOARD",
"children": []
},
{
"name": "Masters",
"serverId": "MASTERSVIEW",
"children": [
{
"name": "State",
"serverId": "LOCATIONMASTER",
"children": []
},
{
"name": "City",
"serverId": "CITYMASTER",
"children": []
}
}
]
var y = ["MASTERSVIEW", "CITYMASTER", "LOCATIONMASTER"];
这是我的尝试,但不正确:
var newSet=[];
for(var d=0; d<x.length;d++){
if(x[i].serverId == y[i]){
newSet.push(x[i]);
}
// for inner children comparison
}
答案 0 :(得分:1)
你可以这样做
for(var i in x){
if(y.indexOf(x[i].serverId ) > -1) {
newSet.push(x[i]);
}
}
对于你可以这样做的内在水平
function checker() {
for(var i in x){
var xx = x[i];
if(y.indexOf(xx.serverId ) > -1) {
newSet.push(x[i]);
}
if(xx.children) {
cheker(xx.children);
}
}
}
checker(x); // your data