Suppose I have a list of objects with many keys and I want to keep only certain keys from them. This is how I am doing it.
The Problem with other good solutions on SO are that if a key is not present in the keys to keep it still adds a key, value where the value is undefined.
let data = [{
'a': 1,
'b': 2,
'c': 3
},
{
'a': 1,
'c': 3,
'd': 4
}]
const keys_to_keep = ['a', 'b']
data = data.map((obj) => {
Object.keys(obj).forEach(function(key) {
if(!keys_to_keep.includes(key))
delete obj[key]
});
return obj;
})
Output :
[ { a: 1, b: 2 }, { a: 1} ]
Is there a better way to get this done. Any help is appreciated.