Home  >  Article  >  Web Front-end  >  How can I merge JavaScript objects in an array that share the same key?

How can I merge JavaScript objects in an array that share the same key?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 02:55:02819browse

How can I merge JavaScript objects in an array that share the same key?

Merging JavaScript Objects in an Array with Same Key

To effectively combine array contents from JavaScript objects sharing a common key, one reliable solution involves:

  1. Identifying Existing Elements: Begin by iterating through the array, isolating each object with the specified key using the filter method. For example:
<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>
  1. Merging Values: If a matching object is found, its index is determined, and the values are appended to the existing object's value array:
<code class="javascript">if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value = output[existingIndex].value.concat(item.value);</code>
  1. Adding New Objects: Should a key with no matching object be encountered, it is added as a new object to the output array:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn