Merge objects in array based on property

前端 未结 3 1808
悲哀的现实
悲哀的现实 2020-12-21 08:03

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

va         


        
3条回答
  •  星月不相逢
    2020-12-21 08:32

    Another approach using Lodash with just chain and reduce

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

提交回复
热议问题