[英]How to add object values from an object array based on an object key in Javascript
我想基于另一个对象键从对象数组添加一些对象值。 我想知道如何通过普通的Javascript或使用lodash之类的帮助程序库来实现。
我已经尝试过使用lodash的_.groupBy
和Array.prototype.reduce()
,但是还没有使用。 数据如下所示:
{
"2019-01-04": [
{
"payments": [
{
"sum": "12",
"currency": "€"
}
]
}
],
"2019-01-06": [
{
"payments": [
{
"sum": "50",
"currency": "€"
},
{
"sum": "30",
"currency": "£"
},
{
"sum": "40",
"currency": "Lek"
},
{
"sum": "2",
"currency": "£"
},
{
"sum": "60",
"currency": "£"
}
]
}
]
}
我期望从该日期起sum属性具有所有相同类型的货币的总和的结果:
{
"2019-01-04": [
{
"payments": [
{
"sum": "12",
"currency": "€"
}
]
}
],
"2019-01-06": [
{
"payments": [
{
"sum": "50",
"currency": "€"
},
{
"sum": "92",
"currency": "£"
},
{
"sum": "40",
"currency": "Lek"
}
]
}
]
}
const result = {};
Object.keys(input).forEach(date => {
result[date] = [{ }];
result[date][0].payments = input[date][0].payments.reduce((payments, c) => {
const grp = payments.find(p => p.currency === c.currency);
grp ? grp.sum = +grp.sum + +c.sum : payments.push(c);
return payments;
}, []);
});
给定您提供的数据结构,使用以下方法将提供所需的输出:
function sumByCurrency(history) {
_.forOwn(history, value => {
const newPayments = [];
_.forEach(value["0"].payments, v => {
let existingPayment = _.find(
newPayments,
newPayment => newPayment && newPayment.currency === v.currency
);
if (existingPayment) {
let existingSum = +existingPayment.sum;
let incomingSum = +v.sum;
existingSum += incomingSum ? incomingSum : 0;
existingPayment.sum = "" + existingSum;
} else {
newPayments.push({
currency: v.currency,
sum: v.sum ? v.sum : 0
});
}
});
value["0"].payments = newPayments;
});
return history;
}
使用它传递您的对象,说您将其paymentHistory
sumByCurrency
函数的sumByCurrency
像这样:
sumByCurrency(paymentHistory);
请注意:如果value["0"].payments
不可用,您可能希望进行一些后备/确保它不会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.