如何映射和减少对象数组? [英] How to map and reduce over an array of objects?
本文介绍了如何映射和减少对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从以下对象数组中统计价格:
How do I count the prices together from the following array of objects:
const cars = [
{
price: 10000,
car: 'audi'
},
{
price: 10000,
car: 'audi'
},
{
price: 10000,
car: 'nissan'
},
{
price: 10000,
car: 'nissan'
},
{
price: 20000,
car: 'mazda'
},
{
price: 10000,
car: 'nissan'
},
];
这样我就可以获得一系列对象,总价格为:
So that I would get an array of objects, with the total prices:
const cars = [
{
price: 20000,
car: 'audi'
},
{
price: 30000,
car: 'nissan'
},
{
price: 20000,
car: 'mazda'
}
];
尝试映射数组,然后减少,但我如何保留结构,以便我找回了一系列物品?这是不正确的:
Tried to map over the array, and then reduce, but how do i keep the structure, so that I get back an array of objects? This is incorrect:
const newCarsArray = cars.map(item => {
return(
//cars.reduce ?
)
});
推荐答案
您可以将阵列缩小为汽车键入的对象持有总数,那么将其转换回格式非常简单
You can reduce your array to an object keyed by car, holding the total, then it's pretty simple to convert that back to your format
const cars = [{price: 10000, car: 'audi'},{price: 10000, car: 'audi'},{price: 10000, car: 'nissan'},{price: 10000, car: 'nissan'}, {price: 20000, car: 'mazda'}, {price: 10000, car: 'nissan'}];
var map = cars.reduce((map, car) => {
map[car.car] = map[car.car] ? map[car.car] + car.price : car.price;
return map;
}, {});
console.log(map); // {audi: 20000, nissan: 30000, mazda: 20000}
var array = Object.keys(map).map( car => ({car: car, price: map[car]}));
console.log(array);
这篇关于如何映射和减少对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文