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
}
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};
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With