I have some (potentially very large) array of objects like this:
[
{
'before1' => val,
'same' => val,
'before2' => val
},
...
]
I need an efficient way to replace only some of the keys in the map (i.e. deleting keys won't work for me), and I have a map like this:
keyReplacements = {
'before1' => 'after1',
'same' => 'same',
'before2' => 'after2'
}
I know the same => same
is not necessary in the map, but it's helpful to include as a full translation schema.
Given this key mapping, what's an efficient method to replace my given array of objects with the following result?
[
{
'after1' => val,
'same' => val,
'after2' => val
},
...
]
I've tried the following:
static replaceObjectKeys(objectToReplace, keyMap) {
objectToReplace.map(o =>
Object.keys(o).map((key) => ({ [keyMap[key] || key]: o[key] })
).reduce((objectToReplace, b) => Object.assign({}, objectToReplace, b)))
return objectToReplace
}
But it just returns me the same object with nothing replaced
const newObject = this.replaceObjectKeys(oldObject, keyMap)
console.log("new obj: ", newObject) // this is the same as oldObject
return newObject