[英]In Javascript remove keys from object not in an Array
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. SO 上其他好的解决方案的问题是,如果键中不存在要保留的键,它仍然会添加一个键,值未定义的值。
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: 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.您正在使用
.map()
创建一个新数组,但是您只是将其分配给旧变量。 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.将您想要保留的属性放在
Set
而不是Array
以便可能更快地查找。
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. for/of
循环通常比.forEach()
循环更受青睐,因为它有更好的流控制选项(break、continue、return 等)和更多的编译器优化机会。
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:您可以在
Object.fromEntries
之后使用map
并filter
以仅保留相关键:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.