make javascript variable from string [duplicate] - javascript

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;

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

Going through a object with a variable [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.

Restroing Array Children values via JSON [duplicate]

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

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