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'
}
CodePudding user response:
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[oldKey]){
obj[newKey] = obj[oldKey]
delete obj[oldKey]
}
}
})
return array
}
convertKeys(rows,newKeys)