Home >Web Front-end >JS Tutorial >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!