我的JSON对象如下所示:

[{
  "aid": "1",
  "atitle": "Ameya R. Kadam"
}, {
  "aid": "2",
  "atitle": "Amritpal Singh"
}, {
  "aid": "3",
  "atitle": "Anwar Syed"
}, {
  "aid": "4",
  "atitle": "Aratrika"
}, {
  "aid": "5",
  "atitle": "Bharti Nagpal"
}]


如您所见,名称通过其相关的辅助名称来区分。现在假设我想显示辅助名称:4.我应该为此写什么js?

最佳答案

您可以遍历数组的元素,对每个数组进行测试(如果辅助为4):

var list = [{"aid":"1","atitle":"Ameya R. Kadam"},
        {"aid":"2","atitle":"Amritpal Singh"},
        {"aid":"3","atitle":"Anwar Syed"},
        {"aid":"4","atitle":"Aratrika"},
        {"aid":"5","atitle":"Bharti Nagpal"}
    ];
var length = list.length;
var i;
for (i=0 ; i<length ; i++) {
    if (list[i].aid == 4) {
        alert(list[i].atitle);
        break; // Once the element is found, no need to keep looping
    }
}


将使用“ Aratrika”发出警报

08-25 15:40