Restroing Array Children values via JSON [duplicate] - javascript

This question already has answers here:
Serializing to JSON in jQuery [duplicate]
(11 answers)
Closed 8 years ago.
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.

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 + ')');
});

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];
}

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);

Related

adding a variable while trying to access an object [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
So below I have a variable newVal. Inside that variable are objects such as profileNum1 and inside that userEmail which I can access via
let profile = newVal.profileNum1.userEmail;
which would return a string such as 'users#email.com'
let newVal = JSON.parse(value);
for (let z = 0; z < 100; z++) {
console.log('LOOP HAS BEGAN RUNNING' + z);
let profile = newVal.profileNum1.userEmail;
console.log('LOOK FOR MEEEEEEEEEEEEEE' + profile);
Now I need to basically add the variable z into profileNum in replacement of 1.
I tried achieving this via let profile = newVal.profileNum + z.userEmail;
Which does not work it just returns NaN so I am assuming I am unable to do it that way since with z = 1 during the loop it should return a result when it hits z = 1 in the loop but it still returns NaN. I am pretty stumped on how I can add the variable Z into that and it still use it to select the object profileNum1, profileNum2, etc. Any help would be appreciated =]
Use bracket notation:
let profile = newVal["profileNum" + z].userEmail;
This will parse profileNum0, profileNum1, profileNum2 etc. and access it - basically doing this:
let profile = newVal.profileNum0.userEmail; // When z is 0
let profile = newVal.profileNum1.userEmail; // When z is 1
let profile = newVal.profileNum2.userEmail; // When z is 2

How can I customize my object's property names with specific variable values without hardcoding them? [duplicate]

This question already has answers here:
How do I create a dynamic key to be added to a JavaScript object variable [duplicate]
(2 answers)
Closed 5 years ago.
I am creating a URL Parser for a school project. I first parse the full query from the url into an array, since query members are separated by "&".
var queryString = /\?(\&?\w+\=\w+)+/.exec(urlString))[0].split("&");
Each array member would look like:
arr[i] = "field=value";
I am doing this in an Object constructor in which I need to return an "HTTPObject". For the assignment, the HTTPObject must have a property called "query", and query should have many properties (one for each query field in the url). Why doesn't this work?
queryString.forEach(function(element) {
var elementArr = element.split("=");
this.query.elementArr[0] = elementArr[1];
});
you cannt set a property like that - but you can with bracket notation:
try this
queryString.forEach(function(element) {
var elementArr = element.split("=");
this.query[elementArr[0]] = elementArr[1];
});
You were very close. You can refer to object properties by name, using square brackets...
var queryString = ["name1=value1", "name2=value2"];
var query = {};
queryString.forEach(function(element) {
var elementArr = element.split("=");
query[elementArr[0]] = elementArr[1];
});
var varName = "name1";
console.log("by variable : " + query[varName]); // can use a variable
console.log("by string : " + query["name1"]); // can use a string
console.log("by propname : " + query.name1); // can hardcode the property name
console.log("query object:");
console.log(query);

make javascript variable from string [duplicate]

This question already has answers here:
Dynamic variables names in javascript
(8 answers)
Closed 9 years ago.
I want to make a variable dynamically.
Example-
var a ="pres"+b;
where b is a variable, and then use a as a different variable.
You'll be in a much confortable solution using an object to store values, and the bracket notation :
var store = {};
var theEnd = 'Something';
store['b'+ theEnd] = 10 ;
store['c'+ theEnd] = 20 ;
You can easily iterate in existing keys and values with :
for (var key in store) {
var value = store[key];
console.log(' store has key:' + key + ' having value ' + value);
}
// output :
// store has key bSomething having value 10
// store has key cSomething having value 20
u have to use eval() to do this... but dont be eval! this is not a good style!
Your question is a no logical;
Is normal that a and b are variables|||
You have to use new String("string"); and in your case
var a = new String("pres")+b ;
but you can use simplier var a ="pres"+b;

Is it possible to create a variable based on the value of more than one variable?

For example A = 10, i want to create a variable with the value in it.
Like this: var i10 or if A = 2, i wanna create a variable like this var i2.
For e.g. A = 10 and B = 5, i want a var A10B5, is that possible?
Edit: more information
It is possible, as explained in detail in this question on SO.
A = 10;
B = 5;
window['A' + A + 'B' + B] = 'Hello';
alert(A10B5);
// alerts: Hello
See a demo in this jsfiddle.
I don't see the point of it though though, since you have to keep a reference of the name of this object it's easier to store the value in a local variable inside a function or object that has always the same name or use an array to store the value.
Proposed solution for the intended use:
Use a two-dimensional array:
Calendar[A][B] = 'value';
By creating dynamic variables you will have to rebuild the name of the variable every time you need to access it it. By using a two-dimensional array you can just use the array with both variables, that spares you the code to rebuild the variable name over and over again and makes it easier to read and maintain.
var A = 10, B = 5;
window['A' + A + 'B' + B] = "You should avoid polluting global " +
"scope at all costs.";
alert(A10B5);
Instead you should resort to objects:
var myVars = {}, A = 10, B = 5;
myVars['A' + A + 'B' + B] = "Just like this.";
alert(myVars.A10B5);
You can create dynamic variables with eval() function
var a = 10;
eval("variable" + a + " = a");
this return a variable with name "variable10" and value "10".
Take a look here too!
For more information: w3schools eval()
Hope it helps ^_^
You can have A = 10 and B = A which takes the same amount in a different variable, however, you also can make an if statement like
if(A > 10){ A = 11 }
check this out
`a = 'varname';
str = a+' = '+'123';
eval(str);
alert(varname);
`

Can I create dynamic object names in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript - dynamic variables
Dynamic Javascript variable names
I need to create a number of objects on a page and want to name them sequentially. Is there a way to do this in JavaScript?
for (i=0;i<num;i++){
var obj+i = new myObject("param1","param2");
obj+i.someProperty = value;
}
This way I can dynamically create a varying number of objects (dependent on the value "num") and then set their properties appropriately.
I can do this in PHP, is there a way to do it in JavaScript?
This isn't recommended, but does what you're trying to do (if you're running in a browser and not some other js environment).
for (i = 0; i < num; i++) {
window['obj' + i] = new myObject("param1","param2");
window['obj' + i].someProperty = value;
}
obj0.someProperty;
This works because global variables are actually properties of the window object (if you're running in the browser). You can access properties of an object using either dot notation (myObject.prop) or bracket notation (myObject['prop']). By assigning window['obj' + i], you're creating a global variable named 'obj' + i.
The better option is to use an array or parent object to store your objects.
myObjs = {};
for (i = 0; i < num; i++) {
myObjs['obj' + i] = new myObject("param1","param2");
myObjs['obj' + i].someProperty = value;
}
myObjs.obj0.someProperty;
Or use an array like lots of other answers suggest.
That's what arrays are for, to hold a collection of something:
var objs = [];
for (i=0;i<num;i++){
objs[i] = new myObject("param1","param2");
objs[i].someProperty = value;
}
Dynamic variables are almost always a bad idea.
You can create, and you can set/modify properties of that object.
Modified code:
var obj = {}; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}
I recommend you to use array. as
var obj = []; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}

Categories