如何比较两个json并生成具有相同信息的新对象

时间:2015-08-07 05:21:56

标签: javascript jquery json

我有两个包含JSON对象的数组:xy。我想创建一个新数组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
    }

1 个答案:

答案 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