In JavaScript, you may encounter a situation where you have an array of objects with a common key, and you need to merge their values into a single object. This can be useful for organizing and aggregating data.
For instance, consider the following array of objects:
<code class="javascript">var array = [ { name: "foo1", value: "val1" }, { name: "foo1", value: [ "val2", "val3" ] }, { name: "foo2", value: "val4" } ];</code>
In this example, the objects share the key "name". To merge their values into a single object, you can use the following approach:
<code class="javascript">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);</code>
The output of this code would be an array of two objects:
<code class="javascript">[ { name: "foo1", value: [ "val1", "val2", "val3" ] }, { name: "foo2", value: [ "val4" ] } ]</code>
In this result, the values for the "foo1" key have been merged into a single array, and the "foo2" key remains untouched. This approach allows you to efficiently merge objects in an array that share a common key, consolidating their values into a more organized representation.
The above is the detailed content of How can I merge JavaScript objects in an array that have the same key?. For more information, please follow other related articles on the PHP Chinese website!