Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment to costruct a new object - Is it possible? [duplicate]

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 in stead to create a new object which contains the following properties as:

var n = {
foo: 42,
bar: true
}
like image 352
Radex Avatar asked Apr 15 '17 18:04

Radex


2 Answers

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};
like image 58
Estus Flask Avatar answered Sep 28 '22 00:09

Estus Flask


It sort of is, but you'll need two steps. You can't destructure directly from an object into another object, but you can make this elegant by using ES6 object notation and wrapping it into a function.

function transformObject(object) {
  const { p: foo, q: bar } = object;
  const newObject = {
    foo,
    bar
  };
  return newObject;
}
like image 20
Pedro Castilho Avatar answered Sep 28 '22 00:09

Pedro Castilho