0

I am passing a variable into a function (an array in this case). How do I use a variable in that array to select data from another array which has a key with the same name? I have tried various notation strategies and I'm not able to nail the syntax. Any ideas?

Use Case:

I have a jQuery ajax call, which return a json string.

function runjson(input_array){
    $.ajax({
           url: '/api.php',
           type: 'POST',
       },
       error: function() {
          console.log('An error occurred connecting to server. Please check your network');
       },
       dataType: 'json',
       success: function(json) {
            if (json.status) {
                $.each(json.data.[input_array.myfield], function() {
                    ....do work...
                };
            }else{
                alert(json.message);
            };
        };
    });
}

The kicker her is I have a value in the input array (myfield = mydata).

I also have json.data.myfield which I can access if I hard set it. but I want to get access to that, and bracket notation doesn't seem to work in this way.

I know this function doesn't exactly work, since I reduced it for simplicity in the question.

Thanks!

user1955162
  • 797
  • 2
  • 6
  • 21
  • __`.`__ is causing `Syntax error`, Try `json.data[input_array.api_field]`. Either you access by `.(dot)` notation or use `Bracket notation([])` when `key` is a variable... – Rayon Sep 28 '16 at 05:06
  • That did it Rayon. Many many thanks. If you post as an answer I will accept – user1955162 Sep 28 '16 at 05:09
  • I am flagging this as duplicate.. I think it is more of a _typographical_ error.. – Rayon Sep 28 '16 at 05:11

0 Answers0