Creating Dynamic variables from json response

Posted by c0mrade on Stack Overflow See other posts from Stack Overflow or by c0mrade
Published on 2010-12-25T17:23:50Z Indexed on 2010/12/25 17:54 UTC
Read the original article Hit count: 259

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery