Picking (deconstructing) properties into object literals

Bob Myers rtm at gol.com
Wed Aug 23 03:22:28 UTC 2017


Extending the ways we can construct object literals has been a sort of
theme in JS language design recently, with shorthand object notation in
ES6, and now spread properties. The motivations include conciseness and
readability.

With destructuring assignment, the community decided it made sense to add
syntax to easily destructure selected properties of an object into
variables. With spread properties, the community is deciding it makes sense
to add syntax to easily include all properties from one object into an
object literal. The missing piece is the ability to include selected
properties of an object into an object literal.

When asked by people we are mentoring or teaching how to create an object
containing selected properties from other objects (which happens with
surprising frequency), we usually just tell them to write

```js
{p: a.p, q: a.q, r: b.r, s: b.s}
```

Or sometimes

```js
const {p, q} = a;
const {r, s} = b;
const newObj = {p, q, r, s};
```

Neither of which is ideal. In this proposal, we allow the following syntax:

```js
{ {p, q} = a, {r, s} = b }
```

Here, the `{p, q} = a` is exactly the same production as the spec's
*AssignmentExpression**, as used in destructuring assignment. That includes
the ability to rename properties (`{q1: q2} = a}`), specify defaults (`{q1
= 42} = a`), and pick out nested properties (`{q1: {q11}} = a`). In other
words, we take full advantage of the power of current destructuring
assignment syntax when picking properties into object literals. The sole
new syntactic aspect in this proposal is the ability to place the
*AssignmentExpression* construct *inside* an object literal.

A fuller description of this proposal can be found at
https://github.com/rtm/js-pick-notation.

--
Bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170823/f02073f1/attachment.html>


More information about the es-discuss mailing list