Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-02 02:55:02
Original
818 people have browsed it

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!