对象解析({x,y,... rest})用于列出对象的属性 [英] Object destructuring ({ x, y, ...rest }) for whitelisting properties of an object
问题描述
使用对象休息解构非常简单黑名单对象的属性,如下例所示:
Using Object rest destructuring is straightforward to blacklist properties of an object, like in the following example:
const original = {
a: 1,
b: 2,
c: 3,
evil: "evil",
ugly: "ugly",
};
const { evil, ugly, ...sanitized } = original;
console.log(sanitized); // prints { a: 1, b: 2, c: 3 }
我想知道是否存在一个类似的简单的方法来做同样的事情,但是使用白名单的属性(例如: {a,b,c}
)。很多时候,我必须将可用属性的一部分转换为JSON,而这样的功能会使代码更易于阅读和更安全。
I wonder if there exists a similar terse way to do the same, but using a white list of properties (in the example: { a, b, c }
). Very often, I have to convert a subset of the available properties as JSON, and such a functionality would make the code much more readable and safer.
我发现了一个类似的问题,但这并不完全相同:
在ES6 / ES2015中有一个更简单的方法将一个对象的属性映射到另一个对象?
I found a similar question, but it is not exactly the same problem: Is there a more terse way to map properties of one object to another in ES6/ES2015?
编辑:遗憾的是,下一个代码不起作用,因为它返回原始对象而不是过滤的对象。
It is a pity that the next code doesn't work, as it is returning the original object instead of the filtered one.
const sanitized = {a, b, c} = original;
// sanitized === original
推荐答案
为此,我使用2帮助函数
For this purpose I use 2 helper functions
export const pickProps = (object, ...props) => (
props.reduce((a, x) => {
if (object.hasOwnProperty(x)) a[x] = object[x];
return a;
}, {})
);
export const omitProps = (object, ...props) => {
const no = {...object};
props.forEach(p => delete no[p]);
return no;
};
您还可以执行
const original = {
a: 1,
b: 2,
c: 3,
evil: "evil",
ugly: "ugly",
};
const { a, b, c } = original;
const filtered = { a, b, c };
这篇关于对象解析({x,y,... rest})用于列出对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!