所以我有这个数据
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
}
]
我想根据数据匹配commission_price
和employee_name
commission_date
这里是预期的输出:
[
{
"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
}, {}))
谢谢。
答案 0 :(得分:3)
您可以将组合键用于任意数量的组。
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; }