Change object key using Object.keys ES6
With lodash mapKeys function its quite easy to transform object keys.
let tab = {
abc: 1,
def: 40,
xyz: 50
}
const map = {
abc: "newabc",
def: "newdef",
xyz: "newxyz"
}
// Change keys
_.mapKeys(tab, (value, key) => {
return map[value];
});
// -> { newabc: 1, newdef: 40, newxyz: 50 }
Here's how I solved it. I used a map to map between existing key and new key. Just substitute the map with whatever new values you need. Finally remove old keys from the object using omit
.
var tab = {
abc:1,
def:40,
xyz: 50
}
var map = {
abc : "newabc",
def : "newdef",
xyz : "newxyz"
}
_.each(tab, function(value, key) {
key = map[key] || key;
tab[key] = value;
});
console.log(_.omit(tab, Object.keys(map)));
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}