使用JS中的点运算符从字符串数组中使用键访问JSON对象无法正常工作[重复]

使用JS中的点运算符从字符串数组中使用键访问JSON对象无法正常工作[重复]

问题描述:

This question already has an answer here:

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?

</div>

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

I think this should be like: alert(obj[objKey][0]).