我目前有一段代码,可以将 .json 文件中的所有信息加载到 JavaScript 中的数组中。
function loadContacts(filter) {
var contacts = (function () {
var contacts = null;
$.ajax({
'async': false,
'global': false,
'url': 'userdata/' + username + '.json',
'dataType': "json",
'success': function (data) {
contacts = data;
}
});
return contacts;
})();
//filter code goes here, not necessary for this example
}
我有一个 ID 号存储在变量中,在本例中为 userid = 99
。下面是我的 .json
文件的示例
[{"firstName":"Ryan","lastName":"Butterworth","id":"99"},{"firstName":"John","lastName":"Doe","id":"101"}]
如何编辑上面的 loadContacts
函数以仅读取/加载 id 为 99 的 .json 信息?因此上面的 loadContacts
函数会将 {"firstName":"Ryan","lastName":"Butterworth","id":"99"}
返回到 联系人
?
最佳答案
您可以使用 filter()
来做到这一点...
contacts = contacts.filter(function(i) {
return i.id == "99";
});
在迭代现有数组并仅添加从函数返回 true 的项目后,它返回一个新数组。
我将不再讨论同步和异步对话,但我认为这条评论的存在让您了解我对此的感受:p
关于javascript - 在 Javascript 中读取/加载 JSON WHERE 'id' = 'x',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892835/