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',
Solution 1:
For this purpose I use 2 helper functions
exportconstpickProps = (object, ...props) => (
props.reduce((a, x) => {
if (object.hasOwnProperty(x)) a[x] = object[x];
return a;
}, {})
);
exportconstomitProps = (object, ...props) => {
const no = {...object};
props.forEach(p =>delete no[p]);
return no;
};
You can also do
const original = {
a: 1,
b: 2,
c: 3,
evil: "evil",
ugly: "ugly",
};
const { a, b, c } = original;
const filtered = { a, b, c };
Solution 2:
I don't think your way to "blacklist" is good, because it unnecessarily assigns original.evil
to evil
, and original.ugly
to ugly
.
You can try this approach:
constblacklistFilter = (obj, blacklist) => Object.entries(obj)
.filter(([key, value]) => !blacklist.includes(key))
.reduce((obj, [key, value]) => (obj[key] = value, obj), {})
constwhitelistFilter = (obj, whitelist) => Object.entries(obj)
.filter(([key, value]) => whitelist.includes(key))
.reduce((obj, [key, value]) => (obj[key] = value, obj), {})
const original = {
a: 1
,b: 2
,c: 3
,evil: 'evil'
,ugly: 'ugly'
}
console.log(blacklistFilter(original, ['evil', 'ugly']))
console.log(whitelistFilter(original, ['a', 'b', 'c']))
Object.entries()
returns an array of object's keys and corresponding values in format [key, value]
, the filter()
method filters keys based on whether they aren't blacklisted or whether they are whitelisted, and reduce()
method converts the [key, value]
array back to an object (similar method as in this answer).
Post a Comment for "Object Destructuring ({ X, Y, ...rest }) For Whitelisting Properties Of An Object"