To effectively combine array contents from JavaScript objects sharing a common key, one reliable solution involves:
<code class="javascript">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; });</code>
<code class="javascript">if (existing.length) { var existingIndex = output.indexOf(existing[0]); output[existingIndex].value = output[existingIndex].value.concat(item.value);</code>
<code class="javascript">} else { if (typeof item.value == 'string') item.value = [item.value]; output.push(item);</code>
By following these steps, the provided array can be reorganized into the desired output, with all values associated with a particular key merged into a single object within the array.
The above is the detailed content of How can I merge JavaScript objects in an array that share the same key?. For more information, please follow other related articles on the PHP Chinese website!