例如我有这个对象数组
const purchases = [
{
name: 'a',
price: 500
},
{
name: 'a',
price: 1000
},
{
name: 'b',
price: 500
},
{
name: 'b',
price: 500
}
]
如何通过purchases.name有效过滤和计算,创建输出可以像这样
let filteredPurchases = [
{
name: 'a',
price: 1500
},
{
name: 'b',
price: 1000
}
]
答案 0 :(得分:2)
您可以将array#reduce
与Object.values()
一起使用,根据name
值对数据进行分组,并在对象中为同一price
添加name
,然后提取出来所有的价值观。
const purchases = [ { name: 'a', price: 500 }, { name: 'a', price: 1000 }, { name: 'b', price: 500 }, { name: 'b', price: 500 } ],
result = Object.values(purchases.reduce((r,{name, price}) => {
r[name] = r[name] || {name, price : 0};
r[name].price += price;
return r;
},{}));
console.log(result);
答案 1 :(得分:1)
您可以使用Array#reduce
执行一些简单的操作,并使用对象引用来保留索引。
const purchases = [{
name: 'a',
price: 500
},
{
name: 'a',
price: 1000
},
{
name: 'b',
price: 500
},
{
name: 'b',
price: 500
}
];
// object for keeping index
const ref = Object.create(null);
let res = purchases
// iterate over the array
.reduce((arr, o) => {
// check index already defined, if defined add price value
if (o.name in ref) arr[ref[o.name]].price += o.price;
// if not then define index and insert a new object with all property of object
else arr[ref[o.name] = arr.length] = Object.assign({}, o);
// return the array reference
return arr;
// set initial value as an array for result
}, [])
console.log(res);

答案 2 :(得分:1)
const purchases = [
{
name: 'a',
price: 500
},
{
name: 'a',
price: 1000
},
{
name: 'b',
price: 500
},
{
name: 'b',
price: 500
}
];
var result = []
function findSum(array, key) {
let sum = 0;
array.forEach(function(element) {
if(key == element.name) {
sum = sum + element.price;
}
});
return sum;
}
purchases.forEach(function(element) {
let sum = findSum(purchases, element.name);
result[element.name] =({name:element.name,price:sum});
});
console.log("Result obj")
console.log(Object.values(result));

答案 3 :(得分:0)
您可以创建和中间地图以对项目的价格求和,然后迭代它以创建所需的结果:
const purchases = [{
name: 'a',
price: 500
},
{
name: 'a',
price: 1000
},
{
name: 'b',
price: 500
},
{
name: 'b',
price: 500
}
];
const mapped = purchases.reduce((result, item) => {
if (!result[item.name]) {
result[item.name] = item.price;
} else {
result[item.name] = result[item.name] + item.price;
}
return result;
}, {});
const result = Object.keys(mapped).map(key => {
return {
name: key,
price: mapped[key]
};
});
console.log(result);