与对象解构相反

时间:2017-12-07 10:19:05

标签: javascript ecmascript-6

给出以下示例。是否有字段对齐的简写

let myObj = {someField: 'someValue'}
let foo = 'value'

myObj.foo = foo // I would like to do the opposite of object destructuring: const {foo} = myObj. I don't want to repeat foo twice.

2 个答案:

答案 0 :(得分:6)

您可以将Object.assignshort hand property一起使用。

const myObj = {}
const foo = 'value'

Object.assign(myObj, { foo });

console.log(myObj);

答案 1 :(得分:2)

如果你转换你的陈述,你可以这样做:

const foo = 'value';
const myObject = { foo };

或者如果您从const更改为var,那么您可以为myObj分配新对象:

var myObj = {};
const foo = 'value';
myObj = { foo }