Home >Web Front-end >JS Tutorial >How can I group an array of objects by a specific property and consolidate other properties into arrays?
Given an array of objects with group and color properties, the goal is to group the items by their group values, consolidating the color values for each group.
The provided array looks like this:
myArray = [ {group: "one", color: "red"}, {group: "two", color: "blue"}, {group: "one", color: "green"}, {group: "one", color: "black"} ]
The desired output is an array like this:
myArray = [ {group: "one", color: ["red", "green", "black"]}, {group: "two", color: ["blue"]} ]
Below is a JavaScript implementation:
var myArray = [ {group: "one", color: "red"}, {group: "two", color: "blue"}, {group: "one", color: "green"}, {group: "one", color: "black"} ]; var group_to_values = myArray.reduce(function (obj, item) { obj[item.group] = obj[item.group] || []; obj[item.group].push(item.color); return obj; }, {}); var groups = Object.keys(group_to_values).map(function (key) { return {group: key, color: group_to_values[key]}; }); console.log("groups:"); console.log(JSON.stringify(groups, null, 4));
This code creates the desired output, with the items grouped by their group property and their color values consolidated into arrays.
The above is the detailed content of How can I group an array of objects by a specific property and consolidate other properties into arrays?. For more information, please follow other related articles on the PHP Chinese website!