I am trying to merge values in 2 objects from the same array. The objects in this case are similar and the values I want to merge are arrays(Set)
var array = [ { name: "foo1", value: ["val1","val2"] }, { name: "foo1", value: ["val2", "val3"] }, { name: "foo2", value: ["val4"] }, { name: "foo2", value: ["val4","val5"] }, ]; Expected Output
[ { name: "foo1", value: ["val1","val2", "val3"] },{ name: "foo2", value: ["val4","val4", "val5"] } ] My Code
var output = []; array.forEach(function(item) { var existing = output.filter(function(v, i) { return v.name == item.name; }); if (existing.length) { var existingIndex = output.indexOf(existing[0]); let newValue = new Set(output[existingIndex].value).add(item.value) output[existingIndex].value = Array.from(newValue); } else { output.push(item); } }); Output Gotten
[ { name: "foo1", value: ["val1", "val2", ["val2", "val3"]] }, { name: "foo2", value: ["val4", ["val4", "val5"]] }] How can I get the expected output (ES6 would also be preferred)
["val4", "val5"]instead ofvalue: ["val4","val4", "val5"], is that right?