我认为这是一个愚蠢的问题,很简单,但是我在Google和其他资源中找不到任何结果
我有这样的对象数组
const myArr = [
[{
id: 1,
price: 200,
}, {
id: 2,
price: 900,
}, {
id: 3,
price: 100,
}],
[{
id: 5,
price: 100,
}]
];
换句话说,我有一个数组,我的数组包含一个数组,每个内部数组包含一个对象
arr [ [ {},{},{} ] , [ {} ] ]
现在我想得到两件事
算所有产品?
所有产品的总和?
*(每个对象=一种产品)
最佳答案
通过spreading展平为Array.concat()
到单个阵列。
使用Array.reduce()
获取sum
。count
是扁平化数组的长度。
const myArr = [[{"id":1,"price":200},{"id":2,"price":900},{"id":3,"price":100}],[{"id":5,"price":100}]];
const flattened = [].concat(...myArr);
const count = flattened.length;
const sum = flattened.reduce((s, o) => s + o.price, 0);
console.log('count', count);
console.log('sum', sum);