10

I'd like to use ES6 destructuring to assign properties of an object, but can't figure out the syntax.

<= ES5:

var dst = {};  // already in existence, with its own props, methods, etc.
var src = { a: 'foo', b: 'bar', c: 'baz' };
dst.a = src.a;
dst.b = src.b;

>= ES6 (my own made-up, not-working syntax):

let dst = {};
let src = { a: 'foo', b: 'bar', c: 'baz' };
dst[{a, b}] = src;

Is it possible to use destructuring assignment onto an object? What's the correct syntax?

EDIT: In my use case, dst is an object that existed well before needing to merge a subset of src's properties; it is not a new Object created solely to 'borrow' from src.

ericsoco
  • 20,453
  • 20
  • 89
  • 117
  • This doesn't look much like destructuring to me, you could have just cloned the item. – MinusFour Nov 16 '15 at 19:28
  • This is not a duplicate of http://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es6; that question is not asking about assigning to one object a subset of properties from another, it's asking about creating a new object from a subset of properties from another. I'll edit my question to clarify that. – ericsoco Nov 17 '15 at 00:40
  • @MinusFour I can't just clone or `Object.assign()`, because I don't want all of `src`'s properties. In my example, note I'm leaving behind `c: 'baz'`. – ericsoco Nov 17 '15 at 00:43

2 Answers2

12

I think you’re going to have to repeat dst:

({a: dst.a, b: dst.b} = src);
Ry-
  • 199,309
  • 51
  • 404
  • 420
  • 4
    I tried this, but didn't have the parens around it. That caused a syntax error -- I now understand that was because the destructuring assignment was interpreted instead as an object literal. Thanks! – ericsoco Nov 17 '15 at 00:50
  • I've tried this in node v5.6 with `--harmony_shipping` and it doesn't appear to work - "Invalid left-hand side in assignment" – Alnitak Feb 23 '16 at 11:59
  • @Alnitak: V8 doesn’t support all of ES6. Works in Firefox. – Ry- Feb 23 '16 at 14:58
0

The cleanest approach IMO is as follows:

const dist = {a: 'foo', b: 'bar', c: 'baz'};

const {a, b} = dist;

const src = {a, b};

run the example in this codepen