简体   繁体   English

根据属性合并数组中的对象

[英]Merge objects in array based on property

I have an array like so which i am trying to merge so any object that has the name property the same will after the merge contain a list of merged objects 我有一个这样的数组,我正在尝试合并,因此具有name属性的任何对象在合并之后都会包含合并对象的列表

var array = [ 
    {name: "One",
     myList: [Object1, Object2]
    },
    {name: "Two",
     myList: [Object3, Object4]
     },
     {name: "One",
     myList: [Object5, Object6]
     }
]

How do i merge the two 'One' objects so i get something like 我如何合并两个“一个”对象,以便得到类似

var array = [ 
    {name: "One",
     myList: [Object1, Object2, Object5, Object6]
    },
    {name: "Two",
     myList: [Object3, Object4]
     }
]

looking to do this in vanilla javascript 希望在香草javascript中做到这一点

Using reduce : 使用reduce

var merged = array.reduce(function(list, obj) {
    var found = false;
    for (var i = 0; i < list.length; i++) {
        if (list[i].name == obj.name) {
            list[i].myList = list[i].myList.concat(obj.myList);
            found = true;
            break;
        }
    }

    if (!found) {
        list.push(obj);
    }

    return list;
}, []);

Firstly you could remove the duplicate entries and organize the objects inside the myList array. 首先,您可以删除重复的条目并组织myList数组中的对象。 Then, return an array of objects with specified keys, based on the ordered object from the first step. 然后,根据第一步中的排序对象,返回带有指定键的对象数组。

 var array = [{name:"One",myList:['Object1','Object2']},{name:"Two",myList:['Object3','Object4']},{name:"One",myList:['Object5','Object6']}], obj = {}; array.forEach(function(v) { obj[v.name] = (obj[v.name] || []).concat(v.myList) }); var arr = Object.keys(obj).reduce(function(s,a) { s.push({name: a, myList: obj[a]}); return s; }, []); console.log(arr); 

Another approach using Lodash with just chain and reduce 使用Lodash另一种方法是只进行减少

var array = [
    { name: "One", myList: ["Object1", "Object2"] },
    { name: "Two", myList: ["Object3", "Object4"] },
    { name: "One", myList: ["Object5", "Object6"] }
  ];

  const newArray = _.chain(array)
    .reduce((acc, currentValue) => {
      acc[currentValue.name] = (acc[currentValue.name] || []).concat(
        currentValue.myList
      );
      return acc;
    }, {})
    .reduce((acc, currentValue, key) => {
      acc.push({ name: key, myList: currentValue }); 
      return acc;
    }, [])
    .value();

  console.log(newArray);

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

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