Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
how to add key value pair for same key in same object in array of object?

this is my array of object.

const arr = [{"company":"Google","product":"A","sell":34},{"company":"Google","product":"B","sell":31},{"company":"Google","product":"C","sell":64},{"company":"Twitter","product":"A","sell":34},{"company":"Twitter","product":"B","sell":56},{"company":"Twitter","product":"C","sell":48}]

solution which i have tried.

const result = arr.reduce((acc, d) => {
       const found = acc.find(a => a.name === d.name);
            if (!found) {
                acc.push({ name: d.name, [d.value]: d.count })
            }
            else {
                found.push({ [d.value]: d.count });
            }
            return acc;
        }, []);
console.log(result)

expected output should be like below but something wrong in else block

[{ company: "Google", A: 34, B:31, C:64 },{ company: "Twitter", A: 34, B:56, C:48 }] 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You have property names wrong all over your code.

And yes, the else block should just create a new property found[d.product] = d.sell;

const arr = [{
  "company": "Google",
  "product": "A",
  "sell": 34
}, {
  "company": "Google",
  "product": "B",
  "sell": 31
}, {
  "company": "Google",
  "product": "C",
  "sell": 64
}, {
  "company": "Twitter",
  "product": "A",
  "sell": 34
}, {
  "company": "Twitter",
  "product": "B",
  "sell": 56
}, {
  "company": "Twitter",
  "product": "C",
  "sell": 48
}]

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.company);
  if (!found) {
    acc.push({
      name: d.company,
      [d.product]: d.sell
    })
  } else {
    found[d.product] = d.sell;
  }
  return acc;
}, []);
console.log(result)

Other than that current algorithm is O(n^2) if you want it to be linear you could use Map to store data to avoid O(n) lookups

const arr = [{
  "company": "Google",
  "product": "A",
  "sell": 34
}, {
  "company": "Google",
  "product": "B",
  "sell": 31
}, {
  "company": "Google",
  "product": "C",
  "sell": 64
}, {
  "company": "Twitter",
  "product": "A",
  "sell": 34
}, {
  "company": "Twitter",
  "product": "B",
  "sell": 56
}, {
  "company": "Twitter",
  "product": "C",
  "sell": 48
}]

const result = [...arr.reduce((acc, d) => {
  const found = acc.get(d.company); // O(1) lookup

  if (found) {
    found[d.product] = d.sell
  } else {
    acc.set(d.company, {
      name: d.company,
      [d.product]: d.sell
    })
  }

  return acc
}, new Map).values()];
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

const arr = [{ "company": "Google", "product": "A", "sell": 34 }, { "company": "Google", "product": "B", "sell": 31 }, { "company": "Google", "product": "C", "sell": 64 }, { "company": "Twitter", "product": "A", "sell": 34 }, { "company": "Twitter", "product": "B", "sell": 56 }, { "company": "Twitter", "product": "C", "sell": 48 }]

const res = []

arr.forEach(function (item) {
  const idxExist = res.findIndex(el => el.company === item.company)
  if (idxExist === -1) {
    res.push({"company": item['company'], [item['product']]: item['sell']})
  } else {
    res[idxExist][item['product']] = item['sell']
  }
})

console.log(res)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda