gpt4 book ai didi

javascript - 根据数组 javascript 中的日期和名称过滤、匹配、计算

转载 作者:行者123 更新时间:2023-11-29 18:53:11 26 4
gpt4 key购买 nike

所以我有这个数据

const data = [
{
"employee_name": "Employee A",
"commission_date": "14/05/2018",
"commission_price": 9000
},
{
"employee_name": "Employee A",
"commission_date": "17/05/2018",
"commission_price": 5000
},
{
"employee_name": "Employee B",
"commission_date": "18/05/2018",
"commission_price": 2000
},
{
"employee_name": "Employee B",
"commission_date": "18/05/2018",
"commission_price": 5000
},
{
"employee_name": "Employee B",
"commission_date": "19/05/2018",
"commission_price": 500
}
]

我想根据数据匹配 employee_namecommission_date 计算 commission_price

在这里,预期的输出:

[
{
"employee_name": "Employee A",
"commission_date": "14/05/2018",
"commission_price": 9000
},
{
"employee_name": "Employee A",
"commission_date": "17/05/2018",
"commission_price": 5000
},
{
"employee_name": "Employee B",
"commission_date": "18/05/2018",
"commission_price": 7000
},
{
"employee_name": "Employee B",
"commission_date": "19/05/2018",
"commission_price": 500
}
]

我已经尝试基于类似问题的答案,但结果仅基于 employee_name 计算得出。这里是代码

let result = Object.values(data.reduce((r, { employee_name, commission_price }) => {
r[employee_name] = r[employee_name] || { employee_name, commission_price : 0 }
r[employee_name].commission_price += commission_price
return r
}, {}))

谢谢。

最佳答案

您可以对任意数量的组使用组合键。

var data = [{ employee_name: "Employee A", commission_date: "14/05/2018", commission_price: 9000 }, { employee_name: "Employee A", commission_date: "17/05/2018", commission_price: 5000 }, { employee_name: "Employee B", commission_date: "18/05/2018", commission_price: 2000 }, { employee_name: "Employee B", commission_date: "18/05/2018", commission_price: 5000 }, { employee_name: "Employee B", commission_date: "19/05/2018", commission_price: 500 }],
result = Object.values(data.reduce((r, o) => {
var key = ['employee_name', 'commission_date'].map(k => o[k]).join('|');
r[key] = r[key] || { employee_name: o.employee_name, commission_date: o.commission_date, commission_price : 0 };
r[key].commission_price += o.commission_price;
return r;
}, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据数组 javascript 中的日期和名称过滤、匹配、计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com