试图求和数组中对象的值
我有3个对象,每个对象中都有两个字段,其中我声明了值:
let items = [
{
id: 1,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
}
];
因此,如果我是对的,则权重之和将为0.06,而总和为12,两者相乘即为0.72,这意味着我想将权重之和与总和相乘。 / p>
我看到了这样的例子:
const weight = items.reduce((prev, cur) => {
return prev + (cur.weight * cur.pieces);
}, 0);
console.log(weight);
在此示例中,总和仅为0.24。 有人可以帮我吗
编辑:@Robby Cornelissen的评论正确。我这是一种错误的思维方式。
答案 0 :(得分:0)
如果要获得所有物品的总重量,则必须先获取每个物品的重量,然后将它们加在一起。
const sum = (arr) => {
return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)
}
let items = [{
id: 1,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
}
]
const sum = (arr) => {
return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)
}
const totalWeight = sum(items)
console.log(totalWeight)
答案 1 :(得分:-1)
您可以使用import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="torch.nn.functional")
遍历数组,将forEach
和pieces
的值相加:
weight
然后乘以let pieces = 0; // sum of pieces
let weight = 0; // sum of weight
items.forEach(function(elmt){
pieces += elmt.pieces;
weight += elmt.weight;
});
* pieces
:
weight
答案 2 :(得分:-1)
使用class
let items=[{id:1,label:"test",itemname:"testitem",pieces:4,weight:.02},{id:2,label:"test",itemname:"testitem",pieces:4,weight:.02},{id:2,label:"test",itemname:"testitem",pieces:4,weight:.02}];
class total {
weight = 0;
pieces = 0;
get product() {
return this.weight * this.pieces;
}
}
const totalObj = items.reduce((prev, cur) => {
prev.weight += cur.weight;
prev.pieces += cur.pieces;
return prev;
}, new total);
console.log(totalObj.product);