對象數組根據某一相同項合並其他屬性為一個數組


 

對象數組示例:

var objects = [
  {name:'group1', usedCount: 2, color:'red'},
  {name:'group1', usedCount: 1, color:'blue'},
  {name:'group1', usedCount: 1, color:'orange'},
  {name:'group2', usedCount: 2, color:'blue'},
  {name:'group2', usedCount: 2, color:'red'},
  {name:'group3', usedCount: 1, color:'red'},
  {name:'group3', usedCount: 4, color:'red'}
]

分組合並后的結果

[
  {name:'group1', usedCount: 4, color:['red','blue','orange']},
  {name:'group2', usedCount: 4, color:['blue','red']},
  {name:'group3', usedCount: 5, color:['red']}
]

這是根據對象的name進行合並,合並后,usedCount累加,color合並為數組。


方法:

var result= objects.reduce((groups, item)=>{   var groupFound= groups.find(arrItem => item.name === arrItem.name);   if(groupFound) {     groupFound.usedCount += item.usedCount;     if(groupFound.color.indexOf(item.color)  == -1) {  //去重       groupFound.color.push(item.color);     }   } else {     //不要直接在原來的對象修改,新建對象     var newGroup = {         name: item.name,         usedCount: item.usedCount,         color: [item.color]     }     groups.push(newGroup);   }   return groups; },[]); console.log(result);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM