Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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,
    }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!