在 JavaScript 中读取/加载 JSON,其中 'id' = 'x'

Read/load JSON in Javascript WHERE 'id' = 'x'

本文关键字:id 其中 JavaScript 读取 JSON 加载      更新时间:2023-09-26

我目前有一段代码可以将.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函数以仅读取/加载 id99 的 .json 信息?所以上面的loadContacts函数会{"firstName":"Ryan","lastName":"Butterworth","id":"99"}返回到contacts

您可以使用

filter()来做到这一点...

contacts = contacts.filter(function(i) {
    return i.id == "99";
});

在遍历现有数组并仅添加从函数返回 true 的项后,它会返回一个新数组。

我将远离同步和异步对话,但我认为这个评论在这里的事实让你了解我对此的感受:p