I want to be able to rename keys in an array of objects. I know how to do them manually, one by one. But what I want to do is rename the keys from another object.
My data:
let data = [
{f_name: 'Harry', l_name: 'Potter', address: 'Godrics Hollow', colors:'red'},
{f_name: 'Ron', l_name: 'Weasley', address: 'The Burrow', colors:'orange'},
{f_name: 'Hermione', l_name: 'Granger', address: '123 London', colors: 'blue'},
];
My object looks like:
let obj = {'first_name': 'f_name', 'last_name': 'l_name', 'home': 'address'};
As you can see the values in obj
match the keys in data
.
I want to be able to rename the keys in data
with the keys in obj
.
I am able to do it with one value like:
let colorName = 'colors';
const rename = data.map(d => {
return ({colorName: d[colorName]});
});
I am not sure how to do this with the obj
.
How do I get my final data
to look like:
data = [
{first_name: 'Harry', last_name: 'Potter', home: 'Godrics Hollow', colorName:'red'},
{first_name: 'Ron', last_name: 'Weasley', home: 'The Burrow', colorName:'orange'},
{first_name: 'Hermione', last_name: 'Granger', home: '123 London', colorName: 'blue'},
];