• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

161
Vistas
transformar una matriz de objetos en una matriz de objetos con un formato diferente

Hay un caso de uso en el que data deben transformarse en un result con el fin de mostrar los datos en la interfaz de usuario en un formato dinámico. Como result , las teclas numeradas son los números de mes y sus valores son la cantidad para ese mes.

 const data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; const result = [ { year: 2021, 10: 47, 11: 58, 12: 96 }, { year: 2022, 1: 88, 2: 90 } ];

Hasta ahora he creado un intermediate , pero no sé cómo incluirlo en el formato de result final de manera concisa. Se prefieren las soluciones ES6.

 const data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; const intermediate = data.map(o => { // eslint-disable-next-line no-unused-vars const [month, day, year] = o.date.split('/'); // destructuring assignment return { year: year, [month]: o.quantity } }); console.log(intermediate);

over 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Actualizado: de intermediate a result

 const intermediate = [ { '10': 47, 'year': '2021' }, { '11': 58, 'year': '2021' }, { '12': 96, 'year': '2021' }, { '1': 88, 'year': '2022' }, { '2': 90, 'year': '2022' } ] const yearDataMap = {} intermediate.forEach(dto => { const storageObj = {} // temp store object Object.entries(dto).forEach(([key, value]) => { // destructure object props if(key === 'year') { storageObj['year'] = value }else { storageObj['month'] = key storageObj['quantity'] = value } }) const {year, month, quantity} = storageObj if (!yearDataMap[year]){ // if no entries with this year preset it with year record yearDataMap[year] = { year } // same as = { year: year } } yearDataMap[year][month] = quantity }) const yearsArr = Object.values(yearDataMap) console.log(yearsArr)

De given a result :

 const data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; const yearDataMap = {} // map to store dates by year data.forEach(dto => { const {date, quantity} = dto const [month, day, year] = date.split('/') if (!yearDataMap[year]){ // if no entries with this year preset it with year record yearDataMap[year] = { year } // same as = { year: year } } yearDataMap[year][month] = quantity // adding quantity by month }) const yearDataArr = Object.values(yearDataMap) // get rid of map and get the `result` console.log(yearDataArr)

over 3 years ago · Juan Pablo Isaza Denunciar

0

Tu enfoque no estuvo mal. construí sobre eso. el objetivo era llenar un objeto global. eso fue todo.

 globalObj = {} data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; data.forEach((o) => { [month, day, year] = o.date.split('/'); if (!globalObj[year]) { globalObj[year] = { year } } globalObj[year][month] = o.quantity }) const result = Object.values(globalObj) console.log(result)

over 3 years ago · Juan Pablo Isaza Denunciar

0

Una forma de pasar de intermediate a result :

 const data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; const intermediate = data.map(o => { // eslint-disable-next-line no-unused-vars const [month, day, year] = o.date.split('/'); // destructuring assignment return { year: year, [month]: o.quantity } }); let years = [...new Set(intermediate.map(o => o.year))]; let accumulator = Object.assign({}, ...years.map(year => ({[year]: {}}))); intermediate.forEach(o => { accumulator[o.year] = { ...accumulator[o.year], ...o }; }); const result = Object.values(accumulator); console.log(result);

Pero lo anterior contenía más pasos individuales de los necesarios. terminé haciendo esto -

 const data = [ { date: '10/1/2021', quantity: 47 }, { date: '11/1/2021', quantity: 58 }, { date: '12/1/2021', quantity: 96 }, { date: '1/1/2022', quantity: 88 }, { date: '2/1/2022', quantity: 90 }, ]; accumulator = {}; data.forEach(o => { // eslint-disable-next-line no-unused-vars const [month, day, year] = o.date.split('/'); // destructuring assignment accumulator[year] = { ...accumulator[year], year: year, [month]: o.quantity }; }); const result = Object.values(accumulator); console.log(result);

over 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda