gpt4 book ai didi

javascript - 如何根据 Javascript 中的对象键从对象数组添加对象值

转载 作者:行者123 更新时间:2023-12-01 01:23:00 25 4
gpt4 key购买 nike

我想根据另一个对象键从对象数组中添加一些对象值。我想知道如何通过纯 JavaScript 或使用像 lodash 这样的辅助库来实现这一点。

我已经尝试过使用 lodash 的 _.groupByArray.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;
}, []);
});

关于javascript - 如何根据 Javascript 中的对象键从对象数组添加对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54075992/

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