简体   繁体   中英

Get sum of values in object

I have an object that consists of n array items, each containing a name and price key. I'm attempting to retrieve, and sum the values of price in each of the entries. How do I access these values in the first place, and then sum them together?

const items = [
    {
        "name": "A",
        "price": 280000000000,
    },
    {
        "symbol": "B",
        "price": 92000000000,
    },
    {
        "symbol": "C",
        "floorPrice": 96000000000,
    }
]

 const items = [ { "name": "A", "price": 280000000000, }, { "symbol": "B", "price": 92000000000, }, { "symbol": "C", "floorPrice": 96000000000, } ] var price = 0; items.map((item) => { if(item.hasOwnProperty("price")){price+=item.price} else if(item.hasOwnProperty("floorPrice")){price+=item.floorPrice} //... if more property }) console.log(price)

You could use the Array.reduce method available in JavaScript. Since you're objects have different keys for "price" you'd want to check which keys are present to add them to the total sum.

Reduce takes in an accumulator (running total) and current value(current spot in array. It loops through the desired values and adds them to the running total.

const sum = items.reduce((acc, curr)=>{
  if(curr.price){
    return acc + curr.price
  } else {
    return acc + curr.floorPrice
  }
 
 }, 0);

console.log(sum);

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