1

I have a scenario, where I receive an obj from a promise, and need to add some keys of this object to another object. For example:

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

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

Normally I could do like following, but I want to do it with object destructuring

object_2.name = object_1.name;

to have:

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

2 回答 2

3

您可以使用对象属性分配模式 [YDKJS: ES6 & Beyond]对目标对象/属性进行解构分配

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

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

console.log(object_2);

于 2018-06-02T07:28:35.767 回答
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
}
于 2018-06-02T07:36:47.807 回答