简体   繁体   中英

Correct way of object destructuring

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'
};   

You could use a destructuring assignment to a target object/property with a 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);

You can achieve the expected output by using object destructing like this:

// 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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