我有一个产品对象数组,每个产品除了代表所用货币的嵌套对象之外还包含产品价格。
var products = [
{
'id': '1',
'currency': { id:1, name:'Dollar' },
'price': '100'
}, {
'id': '4',
'currency': {
id:2,
name:'Euro',
current_quotation: {
date: '2020-03-02',
quotation: 68
}
},
'price': '300'
}, {
'id': '6',
'currency': { id:1, name:'Dollar' },
'price': '50'
}, {
'id': '16',
'currency': null,
'price': '50'
}, {
'id': '23',
'currency': { id:2, name:'Euro' },
'price': null
}
];
我想要做的是获取一个数组,其中包含每种货币的唯一对象及其价格总和,最好使用 lodash 或 ES6 脚本。我需要的结果是:
var subtotals = [
{currency:'Dollar', total: 150},
{currency:'Euro', total: 300}
]
我尝试了很多样本,但到目前为止还没有成功。我的方法是这样的,但它返回数组中的整个产品对象,这与预期结果相去甚远
let subtotals = state.products.reduce((h, product) => Object.assign(h, { [product.currency?.name]:( h[product.currency?.name] || [] ).concat({currency: product.currency?.name, price: product.price}) }), {})
结果
{
"Euro":[
{"currency":"Euro","price":"300"}
],
"Dolar":[
{"currency":"Dolar","price":"100"},
{"currency":"Dolar","price":"50"}
]
}
请注意,某些产品一开始可能没有货币,因为它的值来自下拉输入。在这种情况下,可以在结果中省略该值。
任何帮助将不胜感激。
最佳答案
假设您想对总计进行求和并得到 300 欧元的总计:
迭代每个currency.name
和price
,将输入转换为一个对象,其键是货币名称,值是找到的该货币名称的累积价格,以便远的。最后,映射对象的条目以获得所需格式的对象数组:
var products = [
{
'id': '1',
'currency': { id:1, name:'Dollar' },
'price': '100'
}, {
'id': '4',
'currency': { id:2, name:'Euro' },
'price': '300'
}, {
'id': '6',
'currency': { id:1, name:'Dollar' },
'price': '50'
}
];
const pricesByName = {};
for (const { currency: { name }, price } of products) {
pricesByName[name] = (pricesByName[name] || 0) + Number(price);
}
const output = Object.entries(pricesByName)
.map(([currency, total]) => ({ currency, total }));
console.log(output);
如果货币或价格为空,请使用 if
语句忽略它们:
var products = [
{
'id': '1',
'currency': { id:1, name:'Dollar' },
'price': '100'
}, {
'id': '4',
'currency': { id:2, name:'Euro' },
'price': '300'
}, {
'id': '6',
'currency': { id:1, name:'Dollar' },
'price': '50'
}, {
'id': '16',
'currency': null,
'price': '50'
}, {
'id': '23',
'currency': { id:2, name:'Euro' },
'price': null
}
];
const pricesByName = {};
for (const { currency, price } of products) {
if (price === null || currency === null) continue;
const { name } = currency;
pricesByName[name] = (pricesByName[name] || 0) + Number(price);
}
const output = Object.entries(pricesByName)
.map(([currency, total]) => ({ currency, total }));
console.log(output);
关于javascript - 如何按键对对象数组进行分组并对嵌套对象属性求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60807092/