jquery - 根据具有特定键值的对象过滤和附加 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"
}
]
解决方案
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>`);
});
}
推荐阅读
- php - Symfony4:收到邮件的解码过程不起作用
- asp.net-core - 主服务器与一组从服务器合作。最佳实践
- java - 在没有 Swing UI 的情况下如何启动引擎来解决我的问题?
- date - 使用带格式的 day()-formula 时错误的日期 - PowerBI
- angular - 使用 Angular 路由器的模块延迟加载
- ruby-on-rails - 如何从rails中的国家下拉列表中将美国列为首选?
- javascript - 重构嵌套循环以获得更好的性能
- java - 从 Java 调用 Kotlin 伴侣 null
- html - Shopify Curreny Switcher 将重定向到另一个商店 url
- groovy - 更新 cucumber-groovy 后,我得到“对'PickleStepTestStep'的访问超出其访问权限”