繁体   English   中英

如何使用 javascript 查找 Array 内对象的值的总和?

[英]How to find the sum of values of objects inside an Array using javascript?

[
  { _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 }
]

我想得到总和(总价

Map 和 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)

 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)

首先,您必须将您的 id 放在引号中,否则会出现编译器错误。 这个 function 会给你总价:

function getPriceTotal(products) {

    let priceTotal = 0;

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

    return priceTotal;
}

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

console.log(getPriceTotal(products));

保持!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM