简体   繁体   English

具有解构的对象属性赋值?

[英]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. 我想使用ES6解构来分配对象的属性,但无法弄清楚语法。

<= ES5: <= 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): > = ES6(我自己编写的,不工作的语法):

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; 编辑:在我的用例中, dst是一个在需要合并src属性子集之前就已存在的对象; it is not a new Object created solely to 'borrow' from src . 它不是一个专门为src “借用”而创建的新对象。

我想你将不得不重复dst

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

The cleanest approach IMO is as follows: IMO最干净的方法如下:

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

const {a, b} = dist;

const src = {a, b};

run the example in this codepen 在此codepen中运行示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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