如何使用 ES 标准按数组数据对对象值求和?
How can I sum object values by array data using ES standard?
我有一组对象。每个对象都有一个带有数组列表的“标签”属性。此列表中的值在对象之间重复。我想根据“标签”数组总结“成本”和“收入”。不确定解释是否有意义,但我有以下数据结构。
我希望数据看起来像什么:
const expected =
[ { cost: 500, revenue: 800, tag: 'new' }
, { cost: 800, revenue: 1400, tag: 'equipment' }
, { cost: 1300, revenue: 1650, tag: 'wholesale' }
, { cost: 300, revenue: 600, tag: 'old' }
]
数据是什么样的:
const data =
[ { cost: 500, revenue: 800, tag: [ 'new', 'equipment', 'wholesale' ]}
, { cost: 300, revenue: 600, tag: [ 'old', 'equipment' ]}
, { cost: 800, revenue: 850, tag: [ 'wholesale' ]}
]
A reduce
和 forEach
按标签分组,然后取每个标签的值
var a= [
{
"cost": 500,
"revenue": 800,
"tag": [
"new",
"equipment",
"wholesale"
]
},
{
"cost": 300,
"revenue": 600,
"tag": [
"old",
"equipment"
]
},
{
"cost": 800,
"revenue": 850,
"tag": [
"wholesale"
]
}
]
let x = Object.values(a.reduce((acc,{cost,revenue,tag})=>{
tag.forEach((t) => {
if(!acc[t])acc[t]={tag:t,cost:0,revenue:0}
acc[t].revenue+=revenue
acc[t].cost+=cost
})
return acc;
},{}))
console.log(x)
我有一组对象。每个对象都有一个带有数组列表的“标签”属性。此列表中的值在对象之间重复。我想根据“标签”数组总结“成本”和“收入”。不确定解释是否有意义,但我有以下数据结构。
我希望数据看起来像什么:
const expected =
[ { cost: 500, revenue: 800, tag: 'new' }
, { cost: 800, revenue: 1400, tag: 'equipment' }
, { cost: 1300, revenue: 1650, tag: 'wholesale' }
, { cost: 300, revenue: 600, tag: 'old' }
]
数据是什么样的:
const data =
[ { cost: 500, revenue: 800, tag: [ 'new', 'equipment', 'wholesale' ]}
, { cost: 300, revenue: 600, tag: [ 'old', 'equipment' ]}
, { cost: 800, revenue: 850, tag: [ 'wholesale' ]}
]
A reduce
和 forEach
按标签分组,然后取每个标签的值
var a= [
{
"cost": 500,
"revenue": 800,
"tag": [
"new",
"equipment",
"wholesale"
]
},
{
"cost": 300,
"revenue": 600,
"tag": [
"old",
"equipment"
]
},
{
"cost": 800,
"revenue": 850,
"tag": [
"wholesale"
]
}
]
let x = Object.values(a.reduce((acc,{cost,revenue,tag})=>{
tag.forEach((t) => {
if(!acc[t])acc[t]={tag:t,cost:0,revenue:0}
acc[t].revenue+=revenue
acc[t].cost+=cost
})
return acc;
},{}))
console.log(x)