Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array values to variables [duplicate]

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.

like image 702
SSN Avatar asked Jun 01 '26 13:06

SSN


2 Answers

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); 
});
like image 93
pherris Avatar answered Jun 04 '26 01:06

pherris


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
like image 35
Sotiris Kiritsis Avatar answered Jun 04 '26 03:06

Sotiris Kiritsis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!