如何使用javascript查找数组中对象的值总和?

时间:2020-06-28 11:59:04

标签: javascript arrays object

[
  { _id: 5ee8cfe21ee1ab54643c6c12, name: 'Chicken Zinger Doubles', price: '220', description: "What's better than one Chicken Zinger?!", category: 'Meat & Seafood', file: 'classic-chicken-zinger-combo.jpg', __v: 0 },
  { _id: 5ee8ca618029b65678881c5b, name: 'Coco Cola', price: '45', description: 'Chilled Coco Cola 335ML', category: 'Beverages', file: '960x0.jpg', __v: 0 }
]

我想获取总金额(总计 价格

3 个答案:

答案 0 :(得分:2)

使用Map and Reduce可以解决问题。首先,您需要将价格作为数组获取,然后将这些值中的每一个相加即可得出总计。

let items = [
  { _id: "5ee8cfe21ee1ab54643c6c12", name: 'Chicken Zinger Doubles', price: '220', description: "What's better than one Chicken Zinger?!", category: 'Meat & Seafood', file: 'classic-chicken-zinger-combo.jpg', __v: 0 },
  { _id: "5ee8ca618029b65678881c5b", name: 'Coco Cola', price: '45', description: 'Chilled Coco Cola 335ML', category: 'Beverages', file: '960x0.jpg', __v: 0 },
  { _id: "5ee8cfe21ee1ab54643c6c12", name: 'Chicken Zinger Doubles', price: '420', description: "What's better than one Chicken Zinger?!", category: 'Meat & Seafood', file: 'classic-chicken-zinger-combo.jpg', __v: 0 },
  { _id: "5ee8cfe21ee1ab54643c6c12", name: 'Chicken Zinger Doubles', price: '550', description: "What's better than one Chicken Zinger?!", category: 'Meat & Seafood', file: 'classic-chicken-zinger-combo.jpg', __v: 0 }
];

let total = items.map((i) => i.price).reduce( (a,b) => parseInt(a) + parseInt(b));
console.log(total)

答案 1 :(得分:1)

let arr = [
  { _id: "5ee8cfe21ee1ab54643c6c12", name: 'Chicken Zinger Doubles', price: '220', description: "What's better than one Chicken Zinger?!", category: 'Meat & Seafood', file: 'classic-chicken-zinger-combo.jpg', __v: 0 },
  { _id: "5ee8ca618029b65678881c5b", name: 'Coco Cola', price: '45', description: 'Chilled Coco Cola 335ML', category: 'Beverages', file: '960x0.jpg', __v: 0 }
];

const add = (total, num) => (total + parseInt(num.price))
const total = arr.reduce(add, 0)

console.log(total)

答案 2 :(得分:0)

首先,您必须将ID放在引号中,否则将产生编译器错误。此功能将为您提供总价:

function getPriceTotal(products) {

    let priceTotal = 0;

    for (let product of products) {
        priceTotal += Number(product.price);
    }

    return priceTotal;
}

此函数接受您的对象数组并返回价格总和。例如,如果您有一个名为product的数组,则可以输入以下内容来打印出总数:

console.log(getPriceTotal(products));

保持它!