-3

I have some variables xx=0 , yy=7 stored in array called variables , where variables=[xx,yy] , now i stored these values in a json file , and after parsing back the variables array , I want to restore each variable value ( assign value back ) , what is the perfect way to do this , assuming this example is very simple cause i really have large list of variables.

ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
  • i parsed it already , i want to restore the values within array back to the variables that were assigned to them . – ProllyGeek Dec 18 '13 at 09:58

3 Answers3

1

If your variables are defined globally, you can try

var variablenames = ["xx", "yy"];
var variables = [xx,yy];
for (var i=0; i<variables.length; i++) {
    window[variablenames[i]] = variables[i];
}
Orifjon
  • 915
  • 8
  • 25
  • 1
    `function A() { var b = 1; this.te = function () { console.log(window.b); }; };var a = new A();a.te(); // undefined`. Scopes my friend, scopes. – Eraden Dec 18 '13 at 10:24
  • thats why I wrote If variables are global. If they are scattered in different scopes, it is easier to assign them one by one. – Orifjon Dec 18 '13 at 10:28
1

This isn't good but if you want do this automatically I think you don't find better way.

// String with values
var s = '[1,2,3,4,5,6]';
// Expected variables
var a = ('xx,yy,zz,aa,bb,cc,dd,ee').split(',');
// Changing string in String[]
var m = s.match(/\d+/g);
a.forEach(function (v, i) {
  // Extract value.
  var n = m[i];
  // Prevent change empty value.
  if(n)
    // Set value by evaluation (Be careful, this variable must be in scope!).
    // eval is EVIL!
    eval('(' + v + '=' + n + ')');
});
Eraden
  • 2,818
  • 1
  • 19
  • 17
-1

may be this:

var variables = {};
variables.xx = 100;
variables.yy = 200;

var jsonObj = JSON.stringify(variables); // converted to Json object

console.log(jsonObj); // outputs: {"xx":100,"yy":200} 

var obj1 = JSON.parse(jsonObj);

alert(obj1.xx + "  " + obj1.yy); // alerts (100 200);
patel.milanb
  • 5,822
  • 15
  • 56
  • 92