When destructuring objects in ES6 JS, you can use the { a, b }
syntax in order to create new variables, called a
and b
respectively, from that object. However, as far as I can tell, there is no way to get the keys of the object to automatically create locally-scoped variables with those names. In the following example, I would like to be able to use the hypothetical pseudocode of const {} = args;
and it would generate const a
and const b
automatically.
const bar = { a: 'apple', b: 'ball' };
const foo = (args) => {
const { a, b } = args;
console.log(a, b); // Great!
const {} = args; // I am aware this isn't valid syntax...
console.log(a, b) // Because of course, it doesn't work.
};
foo(bar);
The reason is purely because, outside of this MCVE, I'm actually using a massive object with dozens of keys, and I want to pass certain values from that across into the next part of the promise chain. I can of course use { a: args.a, b: args.b }
, but I'm trying to find the shortest, cleanest way of doing this. I guess what I'm really asking for is PHP's extract()-like syntax but in ES6 JS.
Is this possible?
Ps, I'm aware that this could be seen as a very bad idea if the content of the object is untrusted.
Pps. The environment I'm testing this on is Node 7.9.0