我已经坚持了8天。
让我们说这是我的响应对象数组:
var items = [
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'hp-44',
price: 100,
id: 10,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
]
到目前为止,我已经设法使用reduce来积累价格。这是执行此操作的代码:
var obj = items.reduce( function (allItems, currentItem) {
var item_name = currentItem.name;
var item_price = currentItem.price;
var total_prices = allItems[item_price] = (allItems[item_price] || 0) +
item_price;
var result = {};
result[item_name] = {
item_price: total_prices,
}
return Object.assign(allItems, result);
}, {} )
尽管此方法有效,但它不会返回我想要的结果,而是返回以下内容:
{
'100': 100,
'200': 600,
'250': 500,
'dell-66': { item_price: 600 },
'hp-44': { item_price: 100 },
'acer-33': { item_price: 500 }
}
这就是我想要的并且需要它(顶部没有多余的键/值):
{
'dell-66': { item_price: 600 },
'hp-44': { item_price: 100 },
'acer-33': { item_price: 500 }
}
请问我该如何实现?
答案 0 :(得分:5)
您可以这样做。
const items = [{
name: 'dell-66',
price: 200,
id: 12,
}, {
name: 'hp-44',
price: 100,
id: 10,
}, {
name: 'acer-33',
price: 250,
id: 33,
}, {
name: 'dell-66',
price: 200,
id: 12,
}, {
name: 'acer-33',
price: 250,
id: 33,
}, {
name: 'dell-66',
price: 200,
id: 12,
},
].reduce((res, obj) => {
res[obj.name] = {
item_price: (obj.name in res ? res[obj.name].item_price : 0) + obj.price
}
return res;
}, {})
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:3)
您可以使用以下代码:
var items = [
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'hp-44',
price: 100,
id: 10,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
]
let result = items.reduce((result, current) => {
if(!result[current.name]){
result[current.name] = { item_price: 0 };
}
result[current.name].item_price += current.price;
return result;
}, {})
console.log(result);
答案 2 :(得分:3)
您可以为此使用地图功能。 请尝试以下代码。
<input type="text" name="age">