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.
A couple of improvements.
You're using .map()
which creates a new array, but then you're just assigning it to the old variable. So, you apparently don't need to create a new array at all, you can just iterate the one you have and modify it.
Put the properties you want to keep in a Set
instead of an Array
for potentially faster lookup.
for/of
loops are generally favored over .forEach()
loops because of better flow control options (break, continue, return, etc...) and more opportunities for compiler optimization.
let kv = [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }] const l = new Set(['a', 'b']); for (let obj of kv) { for (let prop of Object.keys(obj)) { if (!l.has(prop)) { delete obj[prop]; } } } console.log(kv);
You can use Object.fromEntries
, after map
and filter
to keep only the relevant keys:
let data = [{'a': 1,'b': 2,'c': 3},{'a': 1,'c': 3,'d': 4}] const keys_to_keep = ['a', 'b'] var result = data.map(obj => Object.fromEntries(keys_to_keep.map(key => obj.hasOwnProperty(key) && [key, obj[key]] ).filter(Boolean)) ); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.