9

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:

  1. It took two statments, and two lines, to create the desired subset object
  2. We had to pollute the local variable scope by creating the intermediary 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?

Jonah
  • 14,529
  • 18
  • 76
  • 146
  • Why does this need a special syntax? Why not use lodash or something, e.g. `var o = {a:1, b: 2, c: 3}; _.pick(o, ['a', 'c'])` – loganfsmyth Jun 22 '15 at 20:12
  • It doesn't *need* it, it would just be nice. I would just create a helper function, rather than bring in all of lodash, if I found myself needing it a lot. This question was specifically about native syntax support -- the problem itself is obviously trivial to solve. – Jonah Jun 22 '15 at 20:17
  • 1
    Totally, just wanted to mention it. – loganfsmyth Jun 22 '15 at 20:24

1 Answers1

4

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)

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • I was afraid of this. It's fine in this example, but becomes verbose when you replace `a` and `c` with long variable names. – Jonah Jun 22 '15 at 20:05