尝试使用一系列过滤器来搜索商店位置的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)
})
答案 0 :(得分:0)
您可以使用#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
int n;
scanf("%d",&n);
int arr[n];
int i;
int p = 0;
int arr_i;
for (arr_i = 0; arr_i < n; arr_i++)
{
scanf("%d",&arr[arr_i]);
}
for (i = 0; i < n; i++)
{
int arr_index=i;
if (arr[arr_index] > 0)
{
p++;
}
}
printf("%d",p);
return 0;
}
,filter
和some
的组合:
Set
const jsonData = [{"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"}]}],
filters = ["Car Wash","ATM Machine"];
const locations = jsonData.filter( location => {
const filterSet = new Set(filters);
return location.services.some( service => {
filterSet.delete(service.alt);
return !filterSet.size;
});
});
console.log(locations);
注意:我为了这个演示片段而删除了Ajax调用。
一个可以在旧浏览器(ES3,主要是IE)中使用的版本,使用jQuery:
.as-console-wrapper { max-height: 100% !important; top: 0; }
var jsonData = [{"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"}]}],
filters = ["Car Wash","ATM Machine"];
var locations = $.grep(jsonData, function (location) {
var filterSet = {};
for (var i = 0; i < filters.length; i++) {
filterSet[filters[i]] = 1;
}
var filtersLeft = filters.length;
$.each(location.services, function (i, service) {
if (filterSet[service.alt]) {
filtersLeft--;
filterSet[service.alt] = 0;
};
return filtersLeft > 0;
});
return filtersLeft === 0;
});
console.log(locations);
.as-console-wrapper { max-height: 100% !important; top: 0; }