3

I have value an array like this:

multi_arr = ["resi_spec","resi_desc"];

So each array value is considered as a variable and I want to store some value of these variables dynamically like this:

resi_spec = "good morning"
resi_desc = "good evening";

So that the array values are converted as variables. Is this possible?

I don't want use use obj[resi_spec] like this and i used array not variable if i just enter resi_spec means , i'll get good morning.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
SSN
  • 846
  • 2
  • 7
  • 20

4 Answers4

6

You could use an object to hold the values:

var multi_arr = ["resi_spec","resi_desc"];
var resi = {};
multi_arr.forEach(function(val) { 
    resi[val] = "good morning"; 
});

Obviously you will want to set different values for each object attribute which you could accomplish with a helper function:

var lookupHelper = function(key) {
    if (key == 'resi_spec') return 'good morning';
    if (key == 'resi_desc') return 'good evening';
};
var multi_arr = ["resi_spec","resi_desc"];
var resi = {};
multi_arr.forEach(function(val) { 
    resi[val] = lookupHelper(val); 
});
pherris
  • 17,195
  • 8
  • 42
  • 58
  • 2
    Good approach, although the `forEach` method is going to be quite useless if you want to have different values. However you could use another array for those… – Sebastian Simon Sep 14 '15 at 13:10
  • To set different values, you would just implement a bit of additional code to look up the proper value. I've added an example to show how you would accomplish this. – pherris Mar 15 '17 at 17:38
4

The best way is having an object like bellow

multi_arr = ["resi_spec","resi_desc"];
var obj = {};
obj[multi_arr[0]] = "good morning";
obj[multi_arr[1]] = "good evening";
console.log(obj); //prints Object {resi_spec: "good morning", resi_desc: "good evening"})

you can access variables like bellow

console.log(obj["resi_spec"]); //prints "good morning";
console.log(obj["resi_desc"]); //prints "good evening";
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
4

You could also do the following.. Although not really recommended, since you will be creating global variables. Jsfiddle

var varNames = ["name1", "name2", "name3"];
for(var i = 0; i < varNames.length; i++){
  window[varNames[i]] = i;
}
console.log(name1); // 0
console.log(name2); // 1
console.log(name3); // 2
Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31
-1

Okay, so I misunderstood your question, so here is my edited response.

var multi_arr = ["resi_spec","resi_desc"];

var object = {};

object[multi_arr[0]] = "good morning";
object[multi_arr[1]] = "good evening";

console.log(object);
Corbin
  • 414
  • 5
  • 19