我想基于另一个对象键从对象数组添加一些对象值。我想知道如何通过普通的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"
}
]
}
]
}
答案 0 :(得分:2)
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;
}, []);
});
答案 1 :(得分:0)
鉴于您提供的数据结构,请使用以下方法提供所需的输出:
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(paymentHistory);
请注意:如果value["0"].payments
不可用,您可能希望进行一些后备/确保它不会中断。