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

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

Linda Hamilton
Release: 2024-10-29 18:54:02
Original
203 people have browsed it

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

How to Merge JavaScript Objects in Array with Same Key

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template