Search code examples
javascriptecmascript-6destructuringobject-destructuring

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

Solution

  • 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);