Reputation: 26253
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
.
Upvotes: 10
Views: 11375
Reputation: 1
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
Upvotes: 0
Reputation: 224857
I think you’re going to have to repeat dst
:
({a: dst.a, b: dst.b} = src);
Upvotes: 12