【发布时间】:2018-04-05 14:49:32
【问题描述】:
尝试使用过滤器数组来搜索商店位置的 javascript 对象,我需要使用过滤器数组中的两个过滤器获得完全匹配,该数组现在有 2 个项目,但会有更多。下面的代码有效,但它正在为每个商店查找匹配项。由于 .json 文件中的一个商店没有 ATM 机,因此不应出现在控制台中。任何帮助将不胜感激!
.json:
[
{
"storenumber": "5210",
"services": [
{
"img": "/locator/img/icons/atm.svg",
"alt": "ATM Machine"
},
{
"img": "/locator/img/icons/carwash.svg",
"alt": "Car Wash"
}
]
},
{
"storenumber": "1066",
"services": [
{
"img": "/locator/img/icons/carwash.svg",
"alt": "Car Wash"
}
]
}
]
.js:
var jsonData,
filteredJsonData = [],
filters = ["Car Wash","ATM Machine"];
$.getJSON("/locator/js/locations.json")
.done(function(data) {
jsonData = data;
$.each(jsonData,function(locationsIndex,locationsItem){
var services = locationsItem.services;
$.each(services,function(servicesIndex,servicesItem){
if (servicesItem.alt && ($.inArray(servicesItem.alt,filters) != -1)) {
// This is finding matches in the filters array, but i need to match all items in the array
console.log("Match Found: " + servicesItem.alt + " at Index " + locationsIndex)
filteredJsonData.push(locationsItem)
}
})
})
console.log(filteredJsonData)
})
【问题讨论】:
-
在将它们包含在最终结果中之前,您是否应该考虑所有过滤器结果并找到所有过滤器都存在的结果?只要它们通过任何单个过滤器,听起来您就可以将它们添加到最终结果中。
-
考虑使用每个 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) 来确定被过滤的元素是否与所有过滤器匹配。
-
为什么我的投票被否决了,我在网站上研究了一个上午的这个问题,终于崩溃了并寻求帮助。
标签: javascript jquery arrays json multidimensional-array