通过ES6中的键过滤对象属性 [英] Filter object properties by key in ES6
问题描述
{
item1:{key:'sdfd',value: 'sdfd'},
item2:{key:'sdfd',value:'sdfd'},
item3:{key:'sdfd',value:'sdfd'}
}
我想通过过滤上面的对象来创建另一个对象,所以我有一些类似的东西。 b
$ b
{
item1:{key:'sdfd',value:'sdfd'},
item3:{key: sdfd',value:'sdfd'}
}
我正在寻找一种干净的方式使用Es6来完成这个任务,所以我们可以使用传播操作符。
THanks!
如果您有一个允许的值列表,您可以使用以下方式轻松地将它们保留在对象中:
const raw = {item1:{key:'sdfd',value: 'sdfd'},item2:{key:'sdfd',value:'sdfd'},item3:{key:'sdfd',value:'sdfd'}}; const allowed = ['item1','item3'] ; const filtered = Object.keys(raw).filter(key => allowed.includes(key)).reduce((obj,key)=> {obj [key] = raw [key]; return obj;} ,{}); console.log(已过滤);
使用:
-
Object.keys
列出raw
(t他的原始数据),然后 -
Array.prototype.filter
选择允许列表中存在的键,使用
-
Array.prototype.includes
以确保它们存在
-
-
Array.prototype.reduce
来构建一个只有允许的属性的新对象。
这将使一个浅的副本与允许的属性(但不会复制属性本身)。
为了琐事,如果要从原始数据中删除不需要的字段(我<强>不会建议做,因为它涉及一些丑陋的突变),你可以反转包括
检查如下:
div class =snippetdata-lang =jsdata-hide =falsedata-console =truedata-babel =true>
我正在包括这个例子来显示基于突变的解决方案,但我不建议使用它。
Lets say I have an object:
{
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
}
I want to create another object by filtering the object above so I have something like.
{
item1: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
}
I am looking for a clean way to accomplish this using Es6, so spread operators are available to me. THanks!
If you have a list of allowed values, you can easily retain them in an object using:
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
console.log(filtered);
This uses:
Object.keys
to list all properties inraw
(the original data), thenArray.prototype.filter
to select keys that are present in the allowed list, usingArray.prototype.includes
to make sure they are present
Array.prototype.reduce
to build a new object with only the allowed properties.
This will make a shallow copy with the allowed properties (but won't copy the properties themselves).
For purposes of trivia, if you wanted to remove the unwanted fields from the original data (which I would not recommend doing, since it involves some ugly mutations), you could invert the includes
check like so:
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowed = ['item1', 'item3'];
Object.keys(raw)
.filter(key => !allowed.includes(key))
.forEach(key => delete raw[key]);
console.log(raw);
I'm including this example to show a mutation-based solution, but I don't suggest using it.
这篇关于通过ES6中的键过滤对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!