要使用react,我有一个像这样的对象数组:
{
_id: 1,
items: [
{ goodName: "cake", amount: 10 },
{ goodName: "potato", amount: 11 },
{ goodName: "apple", amount: 15 }
]
}
{
_id: 2,
items: [
{ goodName: "cake", amount: 10 },
{ goodName: "potato", amount: 11 },
{ goodName: "apple", amount: 15 }
]
}
{
_id: 3,
items: [
{ goodName: "cake", amount: 10 },
{ goodName: "potato", amount: 11 },
{ goodName: "apple", amount: 15 }
]
}
现在,我想循环遍历此对象数组,并返回一个数组
包含每种商品的累计价值。我想使用.map()
方法将其设为:
var value = items.map(function(item) {
var amounts = 0;
var amount=[];
for (var i=0; i<=myArr.length; i++) {
if (myArr[i] === item.name) {
amounts=amounts+item.amount;
amount.push(amounts);
}
}
})
但它不起作用。 myArr
是我使用new Set()
和的数组
Array.from()
循环遍历goodName
并返回它的方法。我不知道我用什么方法可以做到,每个人都有另一种方式吗?
答案 0 :(得分:3)
我编写了代码来循环显示您的信息并返回每种优良类型总金额的结果。但是,需要做出一些澄清。
results
就可以包含每个标记对应的项目的信息,即{good1: total1, good2: total2, ...}
var arr = [
{_id: 1, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 2, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 3, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 4, items: [
{goodName: "potato", amount: 1000},
{goodName: "peach", amount: 2000}
]}
];
var results = {};
arr.forEach(arrElmt => {
arrElmt.items.forEach(item => {
results[item.goodName] = (results[item.goodName] || 0) + item.amount;
});
});
var res = JSON.stringify(results);
console.log(res);
答案 1 :(得分:0)
您不能仅使用地图,因为您正在累积项目的值。我会使用reduce:
const arr = [
{_id: 1, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 2, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 3, items: [
{goodName: "cake", amount: 10},
{goodName: "potato", amount: 11},
{goodName: "apple", amount: 15}
]},
{_id: 4, items: [
{goodName: "potato", amount: 1000},
{goodName: "peach", amount: 2000}
]}
];
let results = [].concat.apply([], arr.map(elem => elem.items))
.reduce((results, item) => {
results[item.goodName] = (results[item.goodName] || 0) + item.amount;
return results;
}, {});
document.write(JSON.stringify(results));
JS没有flatMap
,所以[].concat.apply
舞蹈有点奇怪,但任何好的图书馆都会有它。