I have an object with some properties. I would like to extract a few well-know properties, skipping over any that are not present.
Something like this:
let x = {a: 1, b: 2, c: 3};
let y = take a, b, d from x; // Not real JS!
With y
now looking like this:
{a: 1, b: 2} // Note that d is missing!
Is there an operator or method that does this?
Another way to do it is by destructuring:
let {a, b, d} = x;
let y = {a, b, d};
This automatically takes out the properties you want to use.
Then you can put them back together with an object literal, which in ES6 doesn't require you to do { a: a, b : b }
. You can just write { a, b }
instead, if the names are the same.
In this case, a
, b
and d
are also copied.