JavaScript / ES6 -- Replace Some Keys In An Array Of Objects, Given Key Map
I have some (potentially very large) array of objects like this: [ { 'before1' => val, 'same' => val, 'before2' => val }, ... ] I need an efficient way to repla
Solution 1:
Here's a solution using entries:
const arr = [
{
'before1': 1,
'same': 2,
'before2': 3
}, {
'before1': 4,
'same': 5,
}, {
'before1': 6,
'before2': 7
}, {
'same': 8,
'before2': 9
},
];
const keyReplacements = {
'before1': 'after1',
'same': 'same', // this is not necessary
'before2': 'after2'
};
const newArr = arr.map(obj =>
Object.fromEntries(Object.entries(obj).map(([k, v]) => [keyReplacements[k] || k, v]))
);
console.log(newArr);
Solution 2:
Use ES6 map()
arrayObj = arrayObj.map(item => {
return {
value: item.key1,
key2: item.key2
};
});
Post a Comment for "JavaScript / ES6 -- Replace Some Keys In An Array Of Objects, Given Key Map"