js 合並數組對象中的相同項,並統計數量和


let list=[
  {
    id:11,
    name:'apple',
    num:2
  },
   {
    id:11,
    name:'apple',
    num:3
  },
   {
    id:22,
    name:'pig',
    num:2
  },
   {
    id:11,
    name:'apple',
    num:2
  },
]

list = list.reduce((obj, item) => {  
  let find = obj.find(i => i.id === item.id)  
 let _d = {  
    ...item,  
    frequency: 1  
  }  
  find ? (find.num+=item.num,find.frequency++ ): obj.push(_d)  
  return obj  
}, [])

輸出=>

[
{
id: 11,
name: "apple",
frequency:3,
num: 7
},{
id: 22,
name: "pig",
frequency:1,
num: 2,
}
]

WX20210922-091703.png


免責聲明!

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



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