我有这样的东西:
tires: [{
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct2",
quantity: 1
}];
我想要完成的是
tires: [{
name: "fancyProduct1",
quantity: 3
}, {
name: "fancyProduct2",
quantity: 1
}]
有什么最好的方法来解决这个问题吗?
发布于 2018-06-22 15:59:31
可以使用reduce
将数组分组为一个对象。使用Object.values
将对象转换为数组。
let tires = [{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct2","quantity":1}];
let result = Object.values(tires.reduce((c, {name,quantity}) => {
c[name] = c[name] || {name,quantity: 0}
c[name].quantity += quantity;
return c;
}, {}));
console.log(result);
发布于 2018-06-22 16:01:14
使用Reduce可以做到这一点:
var products = { tires: [ {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct2", quantity: 1}] };
var result = products.tires.reduce((acc,current) => {
if (!acc[current.name]) {
acc[current.name] = { name: current.name, quantity: 0};
}
acc[current.name].quantity++;
return acc;
}, {});
var resultArray = Object.values(result);
console.log(resultArray);
发布于 2018-06-22 16:04:49
您可以使用一个简单的Array.forEach()
调用来遍历array
项,并使用Array.find()
检查result
数组中是否存在已迭代的item
,并相应地执行逻辑。
你的代码应该是这样的:
var result = [];
tires.forEach(function(el) {
let found = result.find(o => o.name === el.name);
if (found) {
found["quantity"] += el["quantity"];
} else {
result.push(el);
}
});
演示:
var tires = [{
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct2",
quantity: 1
}];
var result = [];
tires.forEach(function(el) {
let found = result.find(o => o.name === el.name);
if (found) {
found["quantity"] += el["quantity"];
} else {
result.push(el);
}
});
console.log(result);
https://stackoverflow.com/questions/50983171
复制相似问题