I have
var tab = {
abc:1,
def:40,
xyz: 50
}
I want to change the name of abc,def, xyz to something else, is it possible?
I tried
const test = Object.keys(tab).map(key => {
if (key === 'abc') {
return [
a_b_c: tab[key]
]
}
});
console.log(test);
I got many undefined keys.
Here is the full code for replacing keys based on object that maps the values to replace:
const tab = {abc: 1, def: 40, xyz: 50};
const replacements = {'abc': 'a_b_c', 'def': 'd_e_f'};
let replacedItems = Object.keys(tab).map((key) => {
const newKey = replacements[key] || key;
return { [newKey] : tab[key] };
});
This will output an array with three objects where keys are replaced. If you want to create a new object out of them, just:
const newTab = replacedItems.reduce((a, b) => Object.assign({}, a, b));
This outputs: {"a_b_c": 1, "d_e_f": 40, "xyz": 50}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With