Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda