Skip to content Skip to sidebar Skip to footer

Dynamically Assign Value To Undefined Variable

I'm sure there is a simple way to do this, but am stumped for now. I have many variables defined at the top of my script (here is an example of two): var firstVar,secondVar; Then

Solution 1:

Then I have an object which contains those variables:

No, it doesn't. It contains a copy of the value those variables contained as of when you created the object (which is undefined, since you've never assigned a value to them). Once created, there is no ongoing link between the object property you've copied the value to and the variable.

Since the object has no enduring link to the variables, there's no way for getAll to return the information you've said you want.


You've said in a comment that you're building d3 graphs and have the same structure with some variables, and want to avoid repeating yourself. It sounds to me like you want a builder function:

function buildObject(firstVar, secondVar) {
    return { a: {name:firstVar, number:1}, b: {name:secondVar, number:2} };
}

...which you would then use like this:

var obj1 = buildObject("value1", "value2");
// do a graphvar obj2 = buildObject("valueA", "valueB");
// do a graph

...or possibly even something that just takes the variables and produces the graph:

function makeGraph(firstVar, secondVar) {
    buildTheGraph({ a: {name:firstVar, number:1}, b: {name:secondVar, number:2} });
}

I don't think it is, but if it's the names you want, just put them in quotes (and also myArray.push(myObj.prop[e]); should be myArray.push(myObj[prop][e]); and getAll(name) should be getAll("name")), but again there's no link to the variables at all:

// Since they're not used, we don't even need these: var firstVar, secondVar;var myObj = { a: { name: "firstVar", number: 1 }, b: { name: "secondVar", number: 2 } };

functiongetAll(e) {
  var myArray = [];
  for (var prop in myObj) {
    myArray.push(myObj[prop][e]);
  }
  return myArray;
}

var nameVars = getAll("name");
console.log(nameVars);

...but note that having the names doesn't help you get the variable values later (unless you use eval, which you should seek to avoid).

Post a Comment for "Dynamically Assign Value To Undefined Variable"