Destructing an object ({x, y, ... rest}) for properties of a white object

Using Object Restructuring is straightforward for the black properties of an object, as 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 is a similar complicated 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 functionality will make the code more understandable and safe.

I found a similar question, but this is not exactly the same problem: Is there an easier way to map the properties of one object to another in ES6 / ES2015?

Edit: It is a pity that the following code does not work, as it returns the original object, not the filtered one.

const sanitized = {a, b, c} = original;     
// sanitized === original
+4
2

2

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 };
+1

, " " , original.evil evil original.ugly ugly.

:

const blacklistFilter = (obj, blacklist) => Object.entries(obj)
  .filter(([key, value]) => !blacklist.includes(key))
  .reduce((obj, [key, value]) => (obj[key] = value, obj), {})

const whitelistFilter = (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']))
Hide result

Object.entries() [key, value], filter() , , reduce() [key, value] ( , ).

0

Source: https://habr.com/ru/post/1652484/


All Articles