John
John

Reputation: 822

Substitute array values into a loop to create new arrays

I don't program in javascript much so feel free to tell me if this is a crazy idea.

I'd like to take values in an array and build arrays off of those values. For example, using the "people" array below, I want to create empty arrays "jack_test", "john_test", "mary_test", etc.

var people = ["jack","john","mary"];


 for (var i = 0; i < people.length; i++){
  //I'd like to execute code here that would create new arrays like jack_test = [], john_test= [], etc.
 }

UPDATE: poor question, sorry about that. I'm really at a beginners level with this stuff so bear with me. Let's try a little different scenario (sorry if it strays from original question too much):

Say I have an array like "people", though in reality, it'll be much longer. Then I have another array that has associated body weights, i.e.

var weights = [150,180,120]    

For each person, I'd like to take their starting weight in the array "weights" and add some constant to it to form variables (or as @Pointy points out, form property names) "jack_weight","john_weight" etc.

If I've set this up wrong in my mind and there's some more efficient method, please let me know.

Upvotes: 1

Views: 62

Answers (2)

m59
m59

Reputation: 43785

You can't exactly replicate var jack_test = [], which is locally scoped, but you can do this either globally scoped via the window object or locally within any other object.

var people = ["jack","john","mary"];
for (var i = 0; i < people.length; i++) {
  // assigns the property globally
  window[people[i]+'_test'] = []; 
}
console.log(jack_test); // []

This works because in the global scope (i.e. outside of any functions), variables like var x = 'whatever' are assigned to window, so these are synonymous:

var x = 'whatever';
window.x = 'whatever';

Instead of using window, you can assign properties dynamically to any object using the same method.

var myObj = {};
var myProp = 'foo';
myObj[myProp] = 'foo value';
console.log(myObj.foo); // 'foo value'

Upvotes: 1

Pointy
Pointy

Reputation: 413826

You cannot "construct" variable names in JavaScript*, but you can construct object property names.

var people = ["jack","john","mary"], tests = {};


 for (var i = 0; i < people.length; i++){
  //I'd would like to execute code here that would create new arrays like jack_test = [], john_test= [], etc.
  tests[people[i]] = "something";
 }

That will create properties of the "tests" object with names taken from your array. Furthermore, people[i] could be any expression, if you wanted to do something like add prefixes to the names.

* yes I know, there's eval(). edit and globals, which are object properties and thus a special case of the above example really, except with additional hazards ("special" global symbols etc).

Upvotes: 4

Related Questions