Home >Web Front-end >JS Tutorial >How to Group Array Items into Objects in JavaScript?

How to Group Array Items into Objects in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 05:43:16636browse

How to Group Array Items into Objects in JavaScript?

Grouping Array Items into Objects

You're tasked with transforming an array of objects into a new array with grouped objects, where the values for each group are combined into an array. Here's how you can approach this problem:

var myArray = [
  {group: "one", color: "red"},
  {group: "two", color: "blue"},
  {group: "one", color: "green"},
  {group: "one", color: "black"}
];
// Create a mapping of group names to arrays of values
var group_to_values = myArray.reduce(function (obj, item) {
  obj[item.group] = obj[item.group] || [];
  obj[item.group].push(item.color);
  return obj;
}, {});
// Convert the mapping to an array of grouped objects
var groups = Object.keys(group_to_values).map(function (key) {
  return {group: key, color: group_to_values[key]};
});

The resulting groups array will be:

[
  {group: "one", color: ["red", "green", "black"]},
  {group: "two", color: ["blue"]}
]

This approach utilizes the reduce and map array methods to efficiently group and transform the data.

The above is the detailed content of How to Group Array Items into Objects in JavaScript?. 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