Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda