基于关键javascript组合2个数组

时间:2015-12-06 20:10:38

标签: javascript arrays

我正在尝试根据键“parent_id”组合两个数组。这是数组和所需的输出:

数组1:项目组:

var itemGroups = [
  {
    "id":1,
    "value":"Item Group 1",
    "order":1
  },
  {
    "id":4,
    "value":"Item Group 2",
    "order":2
  }, 
  {
    "id":12,
    "value":"Item Group 3",
    "order":4
  }
];

数组2:组中的项目:

var itemChildren = [
  {
    "id":68,
    "value":"An example item from Group 1",
    "parent_id":1
  },
  {
    "id":69,
    "value":"An example item from Group 2",
    "parent_id":4
  }
  {
    "id":76,
    "value":"An example item from Group 3",
    "parent_id":12
  }
];

所需的输出:

var itemGroupsWithChildren = [
  {
    "id":1,
    "value":"Item Group 1",
    "order":1,
    "children":[
      {
        "id":68,
         "value":"An example item from Group 1",
      }     
    ]
  },
  {
    "id":4,
    "value":"Item Group 2",
    "order":2,
    "children":[
      {
        "id":69,
        "value":"An example item from Group 2"
      }     
    ]
  }, 
  {
    "id":12,
    "value":"Item Group 3",
    "order":4,
    "children":[
      {
        "id":76,
        "value":"An example item from Group 3"
      }     
    ]
  }
];

非常感谢任何帮助。感谢。

编辑:

var dataServiceGroups = [
  {"id":65,"value":"Group 1","order":1,"picklist_id":12},
  {"id":118,"value":"Group 2","order":2,"picklist_id":12},
  {"id":120,"value":"Group 2","order":4,"picklist_id":12},
  {"id":222,"value":"Group 3","order":3,"picklist_id":12},
  {"id":223,"value":"Group 4","order":5,"picklist_id":12},
  {"id":224,"value":"Group 5","order":6,"picklist_id":12},
  {"id":225,"value":"Group 6","order":7,"picklist_id":12},
  {"id":226,"value":"Group 7","order":8,"picklist_id":12},
  {"id":227,"value":"Other Group","order":9,"picklist_id":12}
];

var dataServices = [
  {"id":68,"value":"Item From Group 1","order":3,"picklist_id":13,"parent_id":65},
  {"id":228,"value":"Other Service","order":4,"picklist_id":13,"parent_id":227}
];

3 个答案:

答案 0 :(得分:0)

它看起来像这样

itemGroups.map(function(object, index) {
    object["children"] = itemChildren[index];
});

答案 1 :(得分:0)

我建议您将数组2转换为对象,以便您可以轻松地在其中查找内容,然后使用它将数组1映射到您想要的结果中。

看看以下

var itemC = {}

itemChildren.forEach(function(child) {
  var tmp = {};
  tmp['id'] = child.id;
  tmp['value'] = child.value;
  itemC[child.parent_id] = tmp
});
  

var desiredOutput = itemGroups.map(function(item) {
  item[children] = itemC[item.id];
  return item;
})

答案 2 :(得分:0)

为子项创建分组数组,然后添加到组对象:

var groupedChildren = [];

itemChildren.forEach(function(item) {
   var parentID = item.parent_id;      

   //Create the array for the group by parent id
   if(typeof groupedChildren[parentID] == "undefined") {
      groupedChildren[parentID] = [];
   }
   groupedChildren[parentID].push(item);
});

//Now add the grouped children to itemGroups
var itemGroupsWithChildren = itemGroups.map(function(group) {
  group['children'] = groupedChildren[group.id] || []; //put empty array if no children
  return group;
});