首页 > 解决方案 > 根据具有特定键值的对象过滤和附加 AJAX JSON 结果

问题描述

我正在尝试显示具有值“排序”:“列表:”的 3 条记录

我已经尝试了以下两种使用 if 语句过滤结果的方法(在下面注释掉)来显示 3 条记录,但是这两种方法都没有将任何结果呈现到屏幕上?将以下行注释掉,页面正确呈现所有 5 个结果。任何建议表示赞赏谢谢!

$.ajax({
type: 'GET',
url: '/stores',
success: function(stores) {
  // if (stores.sort === 'list') {
  $.each(stores, function(i, store) {
    // if (stores.sort === 'list'){
      $stores.append(`<div><img src="${store.name}.jpg"></div>`);
    //  }
     });
  //}
   }
 });

我的 JSON 非常简单:

[
 {
 "_id": "5be78df2fb6fc06239e0c39b",
 "name": "Albertsons",
 "sort": "list"
 },
 {
 "_id": "5be78e00fb6fc06239e0c39c",
 "name": "COSTCO",
 "sort": "list"
 },
 {
 "_id": "5be78e17fb6fc06239e0c3ac",
 "name": "Food Lion",
 "sort": "bank"
 },
 {
 "_id": "5be78e34fb6fc06239e0c3b1",
 "name": "7Eleven",
 "sort": "list"
 },
 {
 "_id": "5be78e5ffb6fc06239e0c3b7",
 "name": "Kroger",
 "sort": "bank"
 }
]

标签: jqueryjsonajax

解决方案


stores整个响应,它是一个数组,而不是您正在迭代的单个对象,因此stores.sort没有意义。store改为检查属性:

success: function(stores) {
  $.each(stores, function(i, store) {
    if (store.sort === 'list'){
      $stores.append(`<div><img src="${store.name}.jpg"></div>`);
    }
  });
}

或者,您可以filter事先改为:

success: function(stores) {
  const listStores = stores.filter(({ sort }) => sort === 'list');
  listStores.forEach(({ name }) => {
    $stores.append(`<div><img src="${name}.jpg"></div>`);
  });
}

推荐阅读