簡體   English   中英

如何根據屬性過濾和排列對象數組

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

我有項目的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"
    }
  },
  ]

如果對象具有父級屬性,則應將其包裝在父級的子級道具下。 我發現很難轉換它。 有人可以幫我嗎? 謝謝。

此代碼未經測試,但希望對您有所幫助:

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

要處理的數組(請注意,我為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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM