正确的对象解构方式

时间:2018-06-02 07:24:08

标签: javascript ecmascript-6 object-destructuring

我有一个场景,我从promise中收到一个obj,并且需要将这个对象的一些键添加到另一个对象。例如:

// Received from promise
object_1 = {
    name: 'SH'
};

// Want to add object_1.name to object_2 
object_2 = {
    id: 1234
};

通常我可以这样做,但我想用对象解构

来做
object_2.name = object_1.name;

拥有:

object_2 = {
    id: 1234,
    name: 'SH'
};   

2 个答案:

答案 0 :(得分:3)

您可以将destructuring assignment用于object property assignment pattern [YDKJS: ES6 & Beyond]的目标对象/属性。

var object_1 = { name: 'SH' },
    object_2 = { id: 1234 };

({ name: object_2.name } = object_1);

console.log(object_2);

答案 1 :(得分:1)

您可以通过使用对象破坏来实现预期输出:

// Received from promise
object_1 = {
    name: 'SH'
};

// Want to add object_1.name to object_2 
object_2 = {
    id: 1234
};

object_2 = {
  ...object_2,
  ...object_1
}