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 }
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.
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?
Edit: 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