I am trying to combine an array of object into one object that merges the values of all of the like properties.
objArray = [{
foo: ["f", "b"],
bar: ["e"]
}, {
foo: ["a", "c"],
bar: ["a", "c"]
}, {
foo: ["f", "b"],
bar: ["z"]
}];
const newObj = {
foo: [],
bar: []
};
objArray.forEach((obj) => {
newObj.foo.push(...obj.foo);
newObj.bar.push(...obj.bar);
});
console.log(newObj);
I am getting the desired output with the above code. Is using a forEach loop like above the best way to achieve what I am setting out to do? Ideally I don't want to have to specify the properties to merge, I would like the code to merge identical property names automatically.
Edit:
I need to support IE11