LNA
LNA

Reputation: 1447

How to create an array of variables from an array in Javascript

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:

var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Hermione Granger is a Gryffindor!;;

In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.

for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop 

var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];

The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?

    var myVariables = {}
   ,varNames = ["lunalovegood","dracomalfoy","hermionegranger"]; 
for (var i=0;i<varNames.length;i+=1){

 myVariables[varNames[i]] = 0;
    console.log(lunalovegood);
}

Upvotes: 0

Views: 119

Answers (4)

Alpha Huang
Alpha Huang

Reputation: 1477

var formattedInfo = {}; 
$.each(information, function (i, v) {
    formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});

there is a missing comma at the end of the 1st line of your definition of information.

BTW, I like Harry Potter very much.

Upvotes: 0

user2864740
user2864740

Reputation: 61885

I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.

As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):

// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
  var wizards = [];
  for (var i = 0; i < information.length; i++) {
    var info = information[i];
    var name = info[0];
    // Mapping to named properties means we can forget about indices!
    wizards[name] = {     // <- use Name to map to our Wizard object
        house: info[1],
        // ..
        image: info[7]
    };            
  }
  return wizards;
}

// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);

// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
                       // ^-- property access by Name

Upvotes: 0

Paul S.
Paul S.

Reputation: 66334

Your current approach just needs a most minor tweak to not require the second array.

var students = {}, i;
for (i = 0; i < information.length; ++i)
    students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';

Now the key is set by taking the first item of the Array. You would then do the following for your text,

students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"

You're also missing a , in your information literal.

Upvotes: 3

devnull69
devnull69

Reputation: 16544

This should help you:

Every variable in the global scope can be accessed as a string property of the window object

var myvariable = 4;
alert(window["myvariable"]); // will alert 4

window["newvariable"] = 6;
alert(newvariable);   // will alert 6

Upvotes: 0

Related Questions