Reputation: 19
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 :-)
Upvotes: 1
Views: 205
Reputation: 15003
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.
Upvotes: 0
Reputation: 236122
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 ] );
Upvotes: 2