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

152
Vistas
How can I convert tabular row data to column data in javascript

so I need to convert an array that contains tabular row data into column data in a specific format so I can use it to display a chart with Recharts.

My data is in the following format:

rows = [
    ['Year', '2010', '2011', '2012', '2013'], 
    ['wages','2000','2000','2050','2050'], 
    ['purchase cost', '4000', '4300', '4500', '5000']
]

I need the data to be formatted as follows:

columns = [
    {'Year' : '2010', 'wages' : '2000', 'purchase cost' : '4000'}, 
    {'Year' : '2011', 'wages' : '2000', 'purchase cost' : '4300'}, 
    {'Year' : '2012', 'wages' : '2050', 'purchase cost' : '4500'}, 
    {'Year' : '2013', 'wages' : '2050', 'purchase cost' : '5000'}
]

I've gotten close to getting the result I need but can't seem to get it to work, so I would appreciate any help with this!

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

0

Keep two principles

  1. The subarrays are all the same length.
  2. The first element of the subarray is the column name.

I implemented it in several steps, you can refer to the following code.

const rows = [
  ['Year', '2010', '2011', '2012', '2013'],
  ['wages', '2000', '2000', '2050', '2050'],
  ['purchase cost', '4000', '4300', '4500', '5000']
];

const property = rows.map(row => row[0]);
const columns = rows.map(row => {
  row.shift();
  return row
});

const data = columns.map((column, i) => {
  return column.map(col => {
    const obj = {};
    obj[property[i]] = col;
    return obj;
  });
});

const result = new Array(columns[0].length);
for (let i = 0; i < result.length; i++) {
  const obj = {};
  for (let j = 0; j < property.length; j++) {
    for (const [key, value] of Object.entries(data[j][i])) {
      obj[key] = value;
    }
  }
  result[i] = obj;
}

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