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

守給你的承諾、 提交于 2019-12-18 07:15:15

问题


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
}

回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/43429628/destructuring-assignment-to-costruct-a-new-object-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!