Object property assignment with destructuring?

為{幸葍}努か 提交于 2019-12-10 03:39:34

问题


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.


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/33742755/object-property-assignment-with-destructuring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!