1

I need some help with a javascript principle. I have a variable where part of the variable name is "dynamic". Let me try to explain;

var name_city = "London";
var name_code = "500";

From the webpage I got an value named "type". This will be "city" or "code".

(I just make it manualy here for the sake of this example)

var type = "city";

So with "city" as the value of type, I now want to alert "name_city". But I have no idea on how to do this with javascript.

Does anyone know?

In php I think it will be like this:

$type = "city";

$varname = 'name_'. $type;
echo ${$varname};

I appreciate any help or some clue in the right direction :-)

Chase
  • 29,019
  • 1
  • 49
  • 48
  • Try looking at these: http://stackoverflow.com/questions/7762502/dynamic-javascript-variable-names, http://stackoverflow.com/questions/4385084/javascript-dynamic-variables?lq=1 or http://stackoverflow.com/questions/12826154/can-i-create-dynamic-object-names-in-javascript?lq=1 – Chase Oct 24 '12 at 13:20

2 Answers2

2

In order to accomplish this, you would need to store the data within an object literal, where you can access its keys dynamically. If you write those variables in the global / window object you can access them the same way.

// global scope
var name_city = "London";

var type = "city";

console.log( window[ "name_" + type ] );

This won't work if you aren't in the global scope (which actually, should not be the case at all). So you should store the data in a self-defined object

var data = {
    "name_city":  "London",
    "name_code":  "500"
};

and then do the same thing, just access via

console.log( data[ "name_" + type ] );
jAndy
  • 231,737
  • 57
  • 305
  • 359
0

IF you have several "parallel" variables all describing different aspects of the same entity, you'll almost always be better off using an object instead, i.e.

var name = {city: "London", code: 500};

You can then access the individual attributes by indexing with a variable, e.g. name[type] or by property name, e.g. name.code. A big advantage is that you can treat the object as a unit for purposes like passing it to a function rather than having to pass several different variables.

ebohlman
  • 14,795
  • 5
  • 33
  • 35