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

206
Vistas
¿Cómo sumar valores en objetos con matrices anidadas?

tengo la siguiente estructura:

 groupedData = { rice: [ { name: 'white rice' quantity: 2 category: 'rice' }, { name: 'brown rice' quantity: 1 category: 'rice' } ], water: [ { name: 'sparkle water' quantity: 1 category: 'water' }, { name: 'still water' quantity: 1 category: 'water' } ], tea: [{ name: 'green tea' quantity: 1 category: 'water' }], }

Lo que quiero lograr es tener una cantidad sumada de cada categoría, así: arroz: 3, agua: 2, té: 1

Intenté lo siguiente:

 const sum = () => { let quantity = [] for (var property in groupedData) { for (let i=0; i< groupedData[property].length; i++){ quantity[property] = groupedData[property][i].quantity; } } return quantity; }

pero no devuelve datos sumados sino solo la cantidad del primer artículo [rice: 2, water: 1, tea: 1]

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Su solución no agrega los nodos. Solo agrega la quantity de cada nodo

 const groupedData = { rice: [ { name: 'white rice', quantity: 2, category: 'rice' }, { name: 'brown rice', quantity: 1, category: 'rice' } ], water: [ { name: 'sparkle water', quantity: 1, category: 'water' }, { name: 'still water', quantity: 1, category: 'water' } ], tea: [ { name: 'green tea', quantity: 1, category: 'water' }], }; const sum = () => { let quantity = {} for (var property in groupedData) { for (let i = 0; i < groupedData[property].length; i++) { quantity[property] = quantity[property] ? quantity[property] : 0; quantity[property] += groupedData[property][i].quantity; } } return quantity; }; console.log(sum());

También puede utilizar Object.entries , Array.forEach y Array.reduce para lograrlo.

 const groupedData = { rice: [ { name: 'white rice', quantity: 2, category: 'rice' }, { name: 'brown rice', quantity: 1, category: 'rice' } ], water: [ { name: 'sparkle water', quantity: 1, category: 'water' }, { name: 'still water', quantity: 1, category: 'water' } ], tea: [ { name: 'green tea', quantity: 1, category: 'water' }], }; const sum = () => { let quantity = {}; Object.entries(groupedData).forEach(([key, value]) => { quantity[key] = value.reduce((acc, { quantity }) => acc += quantity, 0) }); return quantity; }; console.log(sum());

about 4 years ago · Juan Pablo Isaza Denunciar

0

Esto se basa en su pregunta.

 const groupedData = { rice: [{ name: 'white rice', quantity: 2, category: 'rice', }, { name: 'brown rice', quantity: 1, category: 'rice', } ], water: [{ name: 'sparkle water', quantity: 1, category: 'water', }, { name: 'still water', quantity: 1, category: 'water', } ], tea: [{ name: 'green tea', quantity: 1, category: 'water', }], } const sum = () => { let quantity = {} for (var property in groupedData) { for (let i = 0; i < groupedData[property].length; i++) { quantity = { ...quantity, [property]: quantity[property] ? quantity[property] + groupedData[property][i].quantity : groupedData[property][i].quantity } } } return quantity; } console.log(sum());

Y esta es mi respuesta con reducir

 const groupedData = { rice: [{ name: 'white rice', quantity: 2, category: 'rice', }, { name: 'brown rice', quantity: 1, category: 'rice', } ], water: [{ name: 'sparkle water', quantity: 1, category: 'water', }, { name: 'still water', quantity: 1, category: 'water', } ], tea: [{ name: 'green tea', quantity: 1, category: 'water', }], } const sum = () => { let res = {} for (var props in groupedData) { const item = groupedData[props].reduce((acc, cur) => { acc += cur.quantity; return acc; }, 0); res[props] = item; } return res; } console.log(sum());

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puedes hacer algo como esto:

 const result = Object.entries(groupedData).reduce((prev, [k, v]) => { const sums = { ...prev, [k]: v.reduce((p, c) => p + c.quantity, 0), } return sums }, {})

Aquí está el fragmento completo:

 const groupedData = { rice: [{ name: 'white rice', quantity: 2, category: 'rice', }, { name: 'brown rice', quantity: 1, category: 'rice', }, ], water: [{ name: 'sparkle water', quantity: 1, category: 'water', }, { name: 'still water', quantity: 1, category: 'water', }, ], tea: [{ name: 'green tea', quantity: 1, category: 'water', }, ], } const result = Object.entries(groupedData).reduce((prev, [k, v]) => { const sums = { ...prev, [k]: v.reduce((p, c) => p + c.quantity, 0), } return sums }, {}) console.log(result)

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