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
If you want to do something with the keys but don't want to define them, why not use Object.keys
or Object.entries
?
const foo = (args) => {
Object.entries(args).forEach(([key, value]) => {
console.log(key, value);
});
};
foo(bar);
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