Destructuring an object into a new object (like Underscore pick but ESier)
Bob Myers
rtm at gol.com
Fri Feb 19 17:55:31 UTC 2016
Indeed, this is the exact objective of the pick notation which I proposed
about six months ago, and have now greatly refined and also implemented a
proof-of-concept.
In the previous incarnation, I called this a "pick operator" and
represented it with `#`, but now I treat it as an extension of dot notation.
What you want is represented as something like
```js
let newObj = obj.{foo, bar};
```
See https://github.com/rtm/js-pick-notation/blob/master/docs/intro.md for a
friendly intro. That repo also contains a spec and the POC with tests.
Regards,
Bob Myers
On Fri, Feb 19, 2016 at 11:02 PM, Zacqary Adam Xeper <
zacqary.xeper at datadoghq.com> wrote:
> So let's say I have:
> let obj = {foo: 1, bar: 2, baz: 3}
>
> And I want to initialize a new object that looks like:
> {foo: obj.foo, bar: obj.bar, quux: 4}
>
> I can create a new object with ALL of these properties using a spread
> operator:
> let newObj = {...obj, quux: 4}
>
> But if I want to initialize a new object that pulls in just the foo and
> bar properties, I have to type this whole structure out:
> let newObj = {foo: obj.foo, bar: obj.bar, quux: 4}
>
> Or, if I want to use shorthand property names, I can use a destructuring
> statement, but then I have to type all the property names twice:
> let {foo, bar} = obj;
> let newObj = {foo, bar, quux: 4};
>
> Underscore.js has a pick function, which looks like this:
> let newObj = {..._(obj).pick(["foo", "bar"]), quux: 4};
>
> but that requires Underscore as a dependency and the syntax is still
> pretty annoying. I feel like this is a common enough task — especially when
> trying to avoid mutating data — that there ought to be a native ES way of
> doing this.
>
> For example, taking a cue from the computed property syntax:
> let newObj = { {foo, bar}: obj, quux: 4 }
>
> This also echoes ordinary destructuring syntax, where the variable names
> are on the left of the equals sign and the object is on the right. Here,
> it's the same, except for initializing objects.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160219/5eaf6798/attachment-0001.html>
More information about the es-discuss
mailing list