javascriptecmascript-6babeljs

Destructuring assignment to construct a new object - Is it possible?


Is it possible to use destructuring assignment syntax to make it possible to extract data objects into another object instead distinct variables?

Example which produce distinct variables (foo, bar):

var {p: foo, q: bar} = {p: 42, q: true};
 
console.log(foo); // 42
console.log(bar); // true  

I would need instead to create a new object which contains the following properties as:

var n = {
    foo: 42,
    bar: true
}

Solution

  • It is not possible. The term destructuring implies that object is destructured to variables.

    A way to not pollute the scope with temporary variables is to use IIFE for destructuring:

    obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
    

    This will assign default values and will pick only valid keys from the object.

    If picking is not necessary, the cleanest recipe to do this with native JS features is ES6 Object.assign:

    obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
    

    Or ES2018 spread:

    obj = { foo: 'foo', bar: 'bar', ...obj};