This is best explained by example. The following works in es6 to create an object consisting of some of the keys of an existing object:
var o = {a:1, b: 2, c: 3}
var {a, c} = o
var subsetObj = {a, c} // will be: {a:1, c:3}
There are two downsides here:
a
and c
variables, which aren't needed locally, except as a means to creating our subset object.Is there a way to accomplish the same thing in a single statement, without introducing the unnecessary locals a
and c
?
There is no specific syntax for this. You can keep doing:
var subsetObj = {a: o.a, c: o.c};
If you have more properties or a variable number of properties, create a helper function.
Related: Is it possible to destructure onto an existing object? (Javascript ES6)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With