1

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?

2 Answers 2

3

No idea what you want to do here:

eval("var " + loc + item.id + "=123;"); // eval is EVIL
alert(loc + item.id); // just creates a string...

Creating dynamic variables is a bad idea. Rather create an object and use key/values.

var branches = {}; // new object, move this to the scope you want to access the value from later
branch[item.id] = 123; // set the key 'item.id' to the value '123'
console.log(branch[item.id]); // retrieve the value of the key 'item.id'

But if you're doing this you can just as well change the structure of your JSON data to something like this:

{"sample":[{"1": {"name": "branch name1", "value": 123}, "2": {"name": "branch name2", "value": 456}}]}

Then just grab the elements of the array and use them like branches above.

Sign up to request clarification or add additional context in comments.

Comments

0

Try the following function to iterate data.sample:

function(i,item){
       window[loc + item.id] = 123;
       alert(window[loc + item.id]);
}

The window object here is used to set a global variable, "dynamically" named on runtime. (This is not a good practice, though.)

If loc = 'branch' and item.id = 2, the alert(window[loc + item.id]) statement would be equivalent to alert(branch2).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.