简体   繁体   English

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

[英]How to filter and arrange object array based on attributes

I have the JSON array of items: 我有项目的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"
    }
  },
  ]

The result should be something like this: 结果应该是这样的:

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"
    }
  },
  ]

If an object has parent properties they should be wrapped under parent's children prop. 如果对象具有父级属性,则应将其包装在父级的子级道具下。 I am finding it very difficult to convert this. 我发现很难转换它。 Can anyone help me out in this? 有人可以帮我吗? Thank you. 谢谢。

This code is NOT tested, but hope it helps: 此代码未经测试,但希望对您有所帮助:

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;
}

The array to process (note that I added an item for p1): 要处理的数组(请注意,我为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"
    }
  },
];

Process the array: 处理数组:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM