如何根据属性过滤和排列对象数组

时间:2014-03-18 21:07:49

标签: javascript arrays json

我有JSON数组项目:

var items = [
  {
    Id: "c1",
    config:{
      url:"/c1",
      content: "c1 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },
    {
    Id: "c2",
    config:{
      url:"/c2",
      content: "c2 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },
      {
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
  ]

结果应该是这样的:

var items = [
  {
    Id: "p1",
    config:{
      url:"/p1",
      content: "p1 content"
    },children:[
      {
        Id: "c1",
        config:{
          url:"/c1",
          content: "c1 content"
          }
      },{
        Id: "c2",
        config:{
          url:"/c2",
          content: "c2 content"
          }
      },
       ]
  },
  {
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
  ]

如果某个对象具有父级属性,则应将其包含在父级子级prop下。我发现很难转换它。任何人都可以帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:1)

此代码未经过测试,但希望有所帮助:

var new_items = [];

for(i in items) {
  var id = items[i].config.parentId;
  if(id) {
    if(!(parent = get_parent(id))) { // If the new list does not contain the parent...
      parent = {Id: id, config: {
        url: items[i].config.parentUrl,
        content: items[i].config.parentContent,
        //... The parent attributes
      }, children: []};
    }
    parent.children.push({/* The child object attributes*/});

  }
}

function get_parent(id) {
  for(ni in new_itmes) {
    if(new_items[ni].Id == id) return new_items[ni];
  }
  return false;
}

答案 1 :(得分:1)

要处理的数组(请注意我为p1添加了一个项目):

var items = [{
    Id: "p1",
    config:{}
  },{
    Id: "c1",
    config:{
      url:"/c1",
      content: "c1 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },{
    Id: "c2",
    config:{
      url:"/c2",
      content: "c2 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },{
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
];

处理数组:

orphans = [];
parents = {};
items.forEach(function(item){
    parents[item.Id]=item;
});
items.forEach(function(item){
  var parent = parents[item.config.parentId];
  if (parent){
    parent.children = parent.children || [];
    parent.children.push(item);
  }else{
    orphans.push(item);
  }
});
console.log('Processed array:', orphans);