简体   繁体   中英

Object property assignment with destructuring?

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 .

我想你将不得不重复dst

({a: dst.a, b: dst.b} = src);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM