简体   繁体   English

将 Javascript 数组中相同对象的属性值相加

[英]Sum up values of identical objects' property in Javascript array

I have the following array:我有以下数组:

[
 { name: "iPhone 12", quantity: 12, price: 325, … },
 { name: "iPhone 12", quantity: 4, price: 325, … },
 { name: "iPhone 13", quantity: 2, price: 525, … },
 { name: "iPhone 12", quantity: 2, price: 325 },
 { name: "iPhone 13", quantity: 3, price: 525 },
 { name: "iPhone SE", quantity: 2, price: 59 }
]

And I want to sum the quantity properties of each object in order to have an array with distinct elements like this:我想总结每个 object 的数量属性,以便拥有一个具有不同元素的数组,如下所示:

[
  { name: "iPhone 12", quantity: 18, price: 325 },
  { name: "iPhone 13", quantity: 5, price: 525 },
  { name: "iPhone SE", quantity: 2, price: 59 }
]

How can I do that?我怎样才能做到这一点?

Seems like a good task for Array.prototype.reduceArray.prototype.reduce来说似乎是一项好任务

 const data = [{ name: "iPhone 12", quantity: 12, price: 325, }, { name: "iPhone 12", quantity: 4, price: 325, }, { name: "iPhone 13", quantity: 2, price: 525, }, { name: "iPhone 12", quantity: 2, price: 325 }, { name: "iPhone 13", quantity: 3, price: 525 }, ] const summed = data.reduce((sum, current) => { const item = sum.find(el => el.name === current.name) if (item) { for (const key in item) { if (key === 'name') continue item[key] += current[key] } } else { sum.push({...current }) } return sum }, []) console.log(summed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在JavaScript中按日期汇总对象属性值 - How to sum up objects property values by date in JavaScript Javascript中新对象数组中数组对象属性值的总和 - Sum of array object property values in new array of objects in Javascript 如果另一个属性具有给定值,则在对象数组中总结某些属性值 - In array of objects sum up certain property values if another property has given value 获取对象数组中的属性值总和 - Get sum of property values within array of objects JavaScript对象数组的子集合中的属性和 - JavaScript sum on property in the sub collection of array of objects 如何在Javascript数组中求和对象的属性 - How to sum objects' property within an array in Javascript 按键汇总Javascript对象数组 - Sum up array of Javascript objects by key 如何基于在对象数组中共享另一个属性名称的值来对一个属性名称的值求和(在 Javascript 中) - How to sum the values of one property name based on sharing the value of another property name in an array of objects (in Javascript) 通过 JavaScript / JQuery 中 object 属性的数组索引对对象数组的所有值求和 - SUM all values of an array of objects by array index of object property in JavaScript / JQuery 如何计算 JavaScript 中对象数组中值的总和? - How to count the sum of values in an array of objects in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM