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

104
Vistas
Update the keys in an object array dynamically

How would I go about updating the keys in an object array dynamically ?

I have the following string array called headers:

headers = ['col1', 'col2', 'col3', 'col4']

I have the object array called rows:

const rows = [
{
  column1: 'value1',
  column2: 'value2',
  column3: 'value3',
  column4: 'value4'
}, 
{
  column1: 'value5',
  column2: 'value6',
  column3: 'value7',
  column4: 'value8'
}
];

I would like to update the keys inside rows so that it matched with the values of the headers done dynamically without hardcoding it.

Expected output to be a string array:

{
  col1: 'value1',
  col2: 'value2',
  col3: 'value3',
  col4: 'value4'
}, 
{
  col1: 'value5',
  col2: 'value6',
  col3: 'value7',
  col4: 'value8'
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

if you have trouble understanding any part let me know

function convertKeys(array , newKeys){
 return array.map(row=>{
    return Object.fromEntries(Object.entries(row).map((x,i)=> {
      x[0] =headers[i]
      return x
    }))
  })
}

convertKeys(rows,headers)

or instead of relying on the order you can use something like this

let newKeys = [
  ["column1", "col1"],
  ["column2", "col2"],
  ["column3", "col3"],
  ["column4", "col4"],
]
function convertKeys(array , newKeys){

  array.forEach(obj=>{
   for (let i = 0 ; i < newKeys.length ; i++){
     let [oldKey,newKey] = newKeys[i]
     if(obj.hasOwnProperty(oldKey)){
       obj[newKey] = obj[oldKey]
       delete obj[oldKey]
     }
       }
 })
  return array
}

convertKeys(rows,newKeys)

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