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

208
Vistas
How to sum values in object with nested arrays?

I have the following structure:

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'
   }],
 }

What I want to achieve is to have a summed quantity of each category, so as: rice: 3, water: 2, tea: 1

I tried the following:

  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;
}

but it doesn't return summed data but only the quantity of the first item [rice: 2, water: 1, tea: 1]

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

0

Your solution does not add the nodes. Just add the quantity of each node

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());

You can also make use of Object.entries, Array.forEach and Array.reduce to achieve this.

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

This is based on your question.

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());

And this is my answer with reduce

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

You can do something like this:

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

Here is the full snippet:

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