Destructuring an object into a new object (like Underscore pick but ESier)

Zacqary Adam Xeper zacqary.xeper at datadoghq.com
Fri Feb 19 17:32:43 UTC 2016


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160219/f1d9f77f/attachment.html>


More information about the es-discuss mailing list