What is the best way to merge array contents from JavaScript objects sharing a key in common?
How can array
in the example below be reorganized into output
? Here, all value
keys (whether an array or not) are merged into all objects sharing the same name
key.
var array = [ { name: "foo1", value: "val1" }, { name: "foo1", value: [ "val2", "val3" ] }, { name: "foo2", value: "val4" } ]; var output = [ { name: "foo1", value: [ "val1", "val2", "val3" ] }, { name: "foo2", value: [ "val4" ] } ];
Here is one option:-
var array = [{ name: "foo1", value: "val1" }, { name: "foo1", value: ["val2", "val3"] }, { name: "foo2", value: "val4" }]; 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]); output[existingIndex].value = output[existingIndex].value.concat(item.value); } else { if (typeof item.value == 'string') item.value = [item.value]; output.push(item); } }); console.dir(output);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With