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

195
Vistas
¿Cómo recalcular un objeto a partir de objetos anidados?

Tengo un objeto donde Citems es una matriz de Object. Cada objeto tiene estado en o de y hora.

 { Chapter: [ { Cname: 'chapter 1', Citems: [{status: 'on', time: 30},{status: 'on', time: 60}], }, { Cname: 'chapter 2', Citems: [{status: 'on', time: 30},{status: 'off', time: 60}] } ], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' }

Quiero generar una matriz u objeto a partir de él que muestre el tiempo total para cada estado como se muestra a continuación

 { on: 120, off: 60 }

Probé con map y reduce pero me confundí.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Solo necesita una 'suma' anidada, aquí implementada usando reduce() y haciendo uso de propiedades calculadas para actualizar el acumulador usando el status como clave.

 const data = { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' }; const result = data.Chapter.reduce((a, { Citems }) => { for (const { status, time } of Citems) { a[status] += time; } return a; }, { on: 0, off: 0 }); console.log(result);

O usando un bucle for...of

 const data = { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' } const result = { on: 0, off: 0 }; for (const { Citems } of data.Chapter) { for (const { status, time } of Citems) { result[status] += time; } } console.log(result);

Para extender esto a una matriz de tales objetos Chapter , podría anidarlo una vez más en reduce() .

 const data = [ { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'on', time: 60 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something', description: 'jfdgljfgdfjgldfkjglfd' }, { Chapter: [{ Cname: 'chapter 1', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 30 }], }, { Cname: 'chapter 2', Citems: [{ status: 'on', time: 30 }, { status: 'off', time: 60 }] }], name: 'Something2', description: 'asdfasdfasdfasdfasdfa' } ] const result = data.reduce((a, { name, Chapter }) => { a[name] = Chapter.reduce((a, { Citems }) => { for (const { status, time } of Citems) { a[status] += time; } return a; }, { on: 0, off: 0 }); return a; }, {}); console.log(result);

about 4 years ago · Santiago Trujillo Denunciar

0

 let obj = {Chapter: [{_id: '624568b157da1d351910c576',Cname:'chapter 1',Citems: [{status: 'on',time: 30},{status: 'on',time: 60}],},{_id:'456a5857da1d351910c577',Cname: 'chapter 2',Citems: [{status:'on',time: 30},{status: 'off',time: 60}]}],_id: '6245f975d17514e0eb9092f7',name:'Something',description:'fdgljfgdfjgldfkjglfd'} console.log(function() { let on=0, off=0; //define return variables (if there is not 'on' or 'off' element at the object, the amount is 0) obj['Chapter'].forEach(function(elem) { if (elem['Citems']) { //if the list item of 'Chapter' does not have a 'Citems' attribute, we will not deal with it elem['Citems'].forEach(function(e) { if (e['status'] == 'on') {on += e['time']} else if (e['status'] == 'off') {off += e['time']} }) } }); return { on: on, off: off } }())

about 4 years ago · Santiago Trujillo 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