Creating Dynamic variables from json response
- by c0mrade
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?