Home >Web Front-end >JS Tutorial >How can you merge objects in a JavaScript array with the same \'name\' key and combine their \'value\' keys into an array?

How can you merge objects in a JavaScript array with the same \'name\' key and combine their \'value\' keys into an array?

DDD
DDDOriginal
2024-10-29 02:25:29759browse

How can you merge objects in a JavaScript array with the same

Merging Objects in Arrays with Shared Key in JavaScript

Problem Statement

Consider an array with objects, where each object has a "name" key. Objects with the same "name" share values. The task is to reorganize the array by merging the "value" keys of all objects with the same "name."

Solution

To merge objects in an array with the same "name" key, you can use the following approach:

<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;
  });
  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>

This solution iterates through the input array, searches for existing objects with the same "name" key, and appends the "value" of the current object to the "value" of the existing object. If there is no existing object, it adds the current object to the output array.

The result of this operation is an array of objects where objects with the same "name" key have their "value" keys merged into an array.

[
  {
    name: "foo1",
    value: ["val1", "val2", "val3"]
  },
  {
    name: "foo2",
    value: ["val4"]
  }
]

The above is the detailed content of How can you merge objects in a JavaScript array with the same \'name\' key and combine their \'value\' keys into an array?. 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