简体   繁体   中英

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 }
]

I want to get the Total Sum (total price )

Map and Reduce will do the trick. You first need to get the prices as an array, then add each of those values to produce your total.

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)

First of all you have to put your id in quotation marks, because otherwise it will give a compiler error. This function will give you the price total:

function getPriceTotal(products) {

    let priceTotal = 0;

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

    return priceTotal;
}

This function accepts an array of your objects and returns the sum of the prices. For example if you had an array called products, you could print out the total by typing in:

console.log(getPriceTotal(products));

Keep it up!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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