Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS object destructuring without defining variable names [duplicate]

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

like image 237
Matt Fletcher Avatar asked Jan 21 '18 16:01

Matt Fletcher


1 Answers

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);
like image 191
coagmano Avatar answered Sep 28 '22 01:09

coagmano