6

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
}
Radex
  • 4,700
  • 11
  • 33
  • 64
  • @torazaburo That topic was the first thing that came to my mind. But I refrained from marking it as a dupe because it's not a dupe question. Only related. The answers intersect only partially. This question is about default values - despite what the title says. – Estus Flask Apr 15 '17 at 21:19

3 Answers3

10

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};
Estus Flask
  • 150,909
  • 47
  • 291
  • 441
1

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;
}
Pedro Castilho
  • 8,408
  • 2
  • 21
  • 37
0

You cannot do it using destructuring, but you could use a helper function like this:

function retag(newStructure, source) {
  var result = {};
  for (var key in newStructure) {
    result[key] = source[newStructure[key]];
  }
  return result;
}

console.log(retag(
  { foo: 'a', bar: 'b' },
  { a: false, b: 42, c: 'unused'}
));
Tamas Hegedus
  • 24,663
  • 9
  • 48
  • 87