Home >Web Front-end >JS Tutorial >How can I merge JavaScript objects with common keys into a new array where values are combined?

How can I merge JavaScript objects with common keys into a new array where values are combined?

DDD
DDDOriginal
2024-11-03 06:53:02804browse

How can I merge JavaScript objects with common keys into a new array where values are combined?

Merging JavaScript Objects with Common Key

In JavaScript, merging objects can be straightforward. However, the process becomes more complex when dealing with an array of objects where multiple objects share a common key and their values need to be combined. Consider the example below:

<code class="js">var array = [
    {
        name: "foo1",
        value: "val1"
    }, {
        name: "foo1",
        value: ["val2", "val3"]
    }, {
        name: "foo2",
        value: "val4"
    }
];</code>

The goal is to reorganize the array into a format where all values associated with the same name key are merged together. The expected output would look like this:

<code class="js">var output = [
    {
        name: "foo1",
        value: ["val1", "val2", "val3"]
    }, {
        name: "foo2",
        value: ["val4"]
    }
];</code>

To achieve this merging, one effective approach involves iterating through the input array and filtering for existing objects with the same name key. If an existing object is found, its value is updated to include the new value. Otherwise, a new object is created and added to the output array.

Here's an example implementation:

<code class="js">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);
    }
});</code>

This approach ensures that the values associated with each name key are correctly merged into a single object within the output array. By iterating through the input array and handling both existing and new objects, it provides a comprehensive solution for merging objects with common keys.

The above is the detailed content of How can I merge JavaScript objects with common keys into a new array where values are combined?. 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