0

In NodeJS, I need to declare a long list of variables based on the contents of a matrix/object. The usual way to do this involves adding them to the global scope.

OLD WAY:

let map = { 'a': 1, 'b': 2, 'c': 3 };

for ( let v in map ){
  global[ v ] = map[ v ];
}

For my purposes, they cannot be global scope. I'm wondering if there's any new way/trick to accomplish this goal in ES6.

For example, destructuring:

for ... // add the function to a local array (A)
let variableNames = [ 'a', 'b', 'c' ];

let [ ...variableNames ] = A;

If nothing like this can be done, then I'll have to think of a different approach.

EDIT

I forgot to clarify that the variables names are dynamic, so current way of de-structuring does not work.

The only left-hand assignment I know that allows for a variable's value to be used as the new variable's name is with object properties:

let o = {}; o[ variable ] = 'something';

I looked around some more, and it seems that I'm asking to dynamically add to the function context/local scope, which is not currently permitted.

Karric
  • 1,415
  • 2
  • 19
  • 32
  • "*I need to declare a long list of variables*" - I don't think so. What is your [actual problem](https://meta.stackexchange.com/q/66377)? Why not just access the values on the object/array from which they come? – Bergi Jun 14 '18 at 19:18

1 Answers1

0

I need to declare a long list of variables based on the contents of a matrix/object:

I'll list you three possible solutions.

Solution 1 (Using Array Destructuring):

let map = { 'a': 1, 'b': 2, 'c': 3 };

var [x, y, z] = Object.values(map);              // saving variables as x, y and z

console.log('x:'+ x + ', y:'+ y+', z:'+z);

Solution 2 (Using Object Destructuring):

let map = { a: 1, b: 2, c: 3 };

var {a:x, b:y, c:z} = map;      // saving variables as x, y and z

console.log('x:'+ x + ', y:'+ y+', z:'+z);

// or

var {a, b, c} = map;      // saving variables as a, b and c

console.log('a:'+ a + ', b:'+ b+', c:'+c);

Solution 3 (Using a local object instead of global Object):

let map = { a: 1, b: 2, c: 3 };
let localObj = {}

Object.keys(map).forEach(key => localObj[key] = map[key])

console.log(localObj);
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
  • `const localObj = map;` would have been much simpler (or `Object.assign({}, map)` if you need to copy) – Bergi Jun 14 '18 at 19:19