0

The JSON object I got was from another PHP file that is called through $.ajax(). For example, I returned from my PHP file a echo json_encode(array('a' => 'b')).

Then, I have the following $.ajax() code:

let objKey = ['a'];

$.ajax({
  type        : 'POST',
  url         : 'phpfilehere.php',
  dataType    : 'json',

  success     : function(obj) {
      alert(obj.objKey[0]);
  }
});

It should have alerted b instead of undefined. Then, I tried alert(obj.a) and it worked. It alerted b. How do I access the value of the JSON object with an array of string which all corresponds to the key of said JSON object?

Richard
  • 7,037
  • 2
  • 23
  • 76

1 Answers1

1

obj.objKey[0] is false in your case, it's good if your object is like :

obj = { 'objKey': ['b'] }

You have two solutions in your case

alert(obj[objKey[0]]);

or

alert(obj.a);

Reference

R3tep
  • 12,512
  • 10
  • 48
  • 75