給定一個具有群組和顏色屬性的物件數組,目標是按組值將項目分組,從而合併顏色每個組的值。
提供的陣列看起來像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中文網其他相關文章!