比较和过滤来自多个数组的数据



目前,我正在构建一个搜索应用程序,该应用程序根据商店特性(自定义分类)id搜索/过滤商店(自定义帖子类型)。最初,我试图使用查询字符串过滤数据,但我找不到一种方法来接收精确匹配,因为您不能使用&&在查询字符串中。

存储功能示例:
Pop - ID
洗车- ID 22
Deli - ID 36
啤酒- ID 54
ATM - id98

商店:
Store -features:54,98,22
Store两个Store -features:54, 55, 36
Store三个Store -features:98, 55, 12

我正在寻找的示例:仅显示包含54和98(存储1)的id的存储。不幸的是,由于我不能使用&&在查询字符串中,它将返回对象中所有三个存储的数组。注:我有大约50家商店和30个不同的商店功能。

我认为最好的前进路径是遍历返回的商店,并将请求的商店特征id与每个单独商店的所有商店特征id进行比较。问题是,到目前为止,我发现检查所有存储特性id是否存在的唯一方法是使用.includes()方法。理论上,它可以工作,但我不能使用它,因为我不知道用户会寻找哪些商店功能。

let storeFeatureID = [array of the store features]
Promise.all([
fetchData(`http://localhost/wordpress/wp-json/wp/v2/locations/?store-features=${storeFeatureID}`),
// "data" in this instance would return three stores since all three stores have either the id of 54 and 98.
]).then((data) => {
const locationData = data[0];
allLocations(locationData);
});
const allLocations = (data) => {
// empty object and array
let storeData = {}, storeArray = [];
// loops through the object
for (let i = 0; i < data.length; i++) {
let myStoresID = data[i]["store-features"];
// checks to see if the store feature ID is within the array. If so, push the store into an empty array(Store Array) and then push it into the empty object (Store Data)
// need a better way to filter this
if ( myStoresID.includes(54) && myStoresID.includes(98)){
console.log('fordata', data[i]);
storeData = data[i];
storeArray.push(storeData);
}
}
let location = storeArray;
let html = "";
let locationAmmount;
//calls sorting fuction
location.sort(dynamicSort("slug"));
for (let j = 0; j < location.length; j++) {
html += `<li><a href="${location[j].link}">${location[j].title.rendered}</a></li>`;
locationAmmount = j;
}
if (locationAmmount >= 0) {
locationAmmount += 1;
document.getElementById("location-container").innerHTML = html;
document.getElementById("feature-results").innerHTML = `<h2>Results: ${locationAmmount}</h2>`;
}
else {
document.getElementById("location-container").innerHTML =
"<h2>Sorry, no results</h2>";
document.getElementById("feature-results").innerHTML = `<h2>Results: 0</h2>`;
}
};

Array.prototype.filter(),Array.prototype.every()Array.prototype.includes()的组合将使您到达那里:

const data=[[
{name:"Store One", "store-features":[54, 98, 22]},
{name:"Store Two","store-features":[54, 55, 36]},
{name:"Store Three","store-features":[98, 55, 12]}
]];
let features=[54,22]; // array of required features (can be any length)
console.log(data[0].filter(st=>features.every(f => st["store-features"].includes(f) ) ) );

如果location是一个实际的JavaScript数组,您可以使用filter(...)

var subarray = location.filter(function(storeID) {
return storeID.includes(54) && storeID.includes(98);
});

例如,如果你的storeid来自复选框,你可以这样做

var subarray = location.filter(function(storeID) {
const filterIDs = document.querySelectorAll("input[checkbox]:checked");
for (var i = 0; i < filterIDs.length) {
if (!storeID.includes(fillterIDs[i].value)) return false;
}
return true;
});

最新更新