给定一个具有组和颜色属性的对象数组,目标是按组值对项目进行分组,从而合并颜色每个组的值。
提供的数组看起来像this:
myArray = [ {group: "one", color: "red"}, {group: "two", color: "blue"}, {group: "one", color: "green"}, {group: "one", color: "black"} ]
所需的输出是这样的数组:
myArray = [ {group: "one", color: ["red", "green", "black"]}, {group: "two", color: ["blue"]} ]
下面是 JavaScript实现:
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));
此代码创建所需的输出,其中项目按其组属性分组,并将其颜色值合并到数组中。
以上是如何按特定属性对对象数组进行分组并将其他属性合并到数组中?的详细内容。更多信息请关注PHP中文网其他相关文章!