5

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

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

3 Answers 3

3

Using 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;
}, []);
Sign up to request clarification or add additional context in comments.

Comments

1

Firstly you could remove the duplicate entries and organize the objects inside the myList array. 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);

4 Comments

You can try obj[v.name] = (obj[v.name] || []).concat(v.myList)
@Rajesh Inside the foreach?
@Kinduser Yes. spread operator is part of ES6 and is not available in all browsers
@blu10 I think everything else would work. You can replace code I suggested inside forEach and it should be good
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.