我有这样的东西:
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
}]
有什么最佳方法的想法吗?
答案 0 :(得分:4)
您可以使用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);
答案 1 :(得分:1)
使用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);
答案 2 :(得分:1)
答案 3 :(得分:-1)
您可以执行以下操作...
var newTries = tires.map(n => (
// logic for new array where you can get attributes of item in tires to create a new array.
console.log(n); // this can show what properties are available in the current item write it to the console.
)};
希望这会有所帮助。