My JSON response looks like this :
{"sample":[{"id":"2","name":"branch name"},{"id":"3","name":"branch name 2"}]}
My function looks like this :
function getJSONObjects(){
$.getJSON("http://localhost/api/branches",
function(data){
$.each(data.sample, function(i,item){
var loc = "branch";
eval("var " + loc + item.id + "=123;");
alert(loc + item.id);
});
});
}
The idea is to create branch + id object so I can do something with it(create marker on a map), so I tried to assign it any value to see if this was working.
I wanted both branch2 and branch3 to alert 123 so I have something to start with. But currently this alerts branch2 and branch3 instead of 123.
I have little experience with creating dynamic variables/objects can someone tell me what I’m doing wrong or maybe another approach towards solving this?
No idea what you want to do here:
Creating
dynamic variablesis a bad idea. Rather create anobjectand use key/values.But if you’re doing this you can just as well change the structure of your JSON data to something like this:
Then just grab the elements of the array and use them like
branchesabove.