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

161
Visualizações
How to sum all Object using index with an arrays

how can I search duplicate data using index key object here is my object :

 const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }

and I have an arrays

const arr = ["product1", "product2" ]

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum 

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

 const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I would use Array.prototype.reduce to iterate through the array and return a single value that is the total price.

    const products = {
        id1: { name: "paper", price: 4 },
        id2: { name: "ball", price: 2 },
        id3: { name: "ice-cream", price: 9 },
    };

    const productIds = ["id1", "id2"];

    const totalPrice = productIds.reduce((sum, id) => {
        return sum + products[id].price;
    }, 0);
about 4 years ago · Juan Pablo Isaza Relatório

0

Your problem is that the obj will never contain the key product1 twice. When that object is created during runtime the last value of product1 is what is stored in the object. Even if you had a JSON object with those two keys, when you go to parse it, the last key will be the value. The only way I can think to do what you want is that you need to change the data prior to the object being created.

You added to unique keys, which isn't going to help you as now you'll need to iterate through all the keys to make sure you are getting all of them. You are better off putting the key in the object, and use an array of objects.

const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

You can then use Array.reduce to combine the values, or other methods.

Now to get only product 1 and 2 use filter:

const desiredProducts = obj.filter(p => ['product1','product2'].includes(p.key));
``

Or you can combine any matching keys using Array.reduce()

```js
const combinedResult = obj.reduce((cur, acc) => {
  const s = cur.find(c => c.key === acc.key);
  if (s)
    s.price += acc.price;
  else
   cur.push(acc);  

}, []);

about 4 years ago · Juan Pablo Isaza Relatório

0

JSON object can't hold duplicate keys. If so, it gets replaced by the last record.

In your case, the input becomes:

const obj = {
  product1: { name: 'paper', price: 2 },
  product2: { name: 'ball', price: 2 },
  product3: { name: 'ice-cream', price: 9 }
}

Your possible input will be like thes:

const obj = {
  product1: [{ name: 'paper', price: 4 }, { name: 'paper', price: 2 }],
  product2: [{ name: 'ball', price: 2 }],
  product3: [{ name: 'ice-cream', price: 9 }]
}
const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

Updated answer as updated code:

const obj = {
  "product1 Hello": {name: 'paper', price: 4},
  "product2 test": {name: 'ball', price: 2},
  "product3 Hello3": {name: 'ice-cream', price: 9},
  "product1 Hello4": {name: 'paper', price: 2}
}
const arr = ["product1", "product2"]

let keys = Object.keys(obj).filter(x => arr.some(y => x.includes(y)))
keys.map(x => obj[x].price).reduce((x, y) => x + y, 0)
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