我有 2 個陣列bodyparts& equipment。
陣列物件已放入下拉選單中。
我正在嘗試filter基于物件值的結果,
例如。如果我選擇“胸部”bodyparts array和“杠鈴”,equipment array我只希望“胸部”和“杠鈴”中具有匹配值的結果出現在console.
這是陣列物件的樣子
{bodyPart: 'neck', equipment: 'body weight', id: '1403', name: 'neck side stretch', …}
const dataDiv = document.getElementById("data")
const apiURL = 'https://exercisedb.p.rapidapi.com/exercises/bodyPart/{chest}'
let mainList = []
let bodypartsList = []
let equipmentList = []
async function getApiURL(endpoint, value) {
console.log(`https://exercisedb.p.rapidapi.com/exercises/${endpoint}/${value}`);
const response = await fetch(`https://exercisedb.p.rapidapi.com/exercises/${endpoint}/${value}`, {
"method": "GET",
"headers": {
"x-rapidapi-host": "exercisedb.p.rapidapi.com",
"x-rapidapi-key": "myApiKey"
}
})
const data = await response.json();
if (endpoint == "bodypart") {
bodypartsList = data
} else {
equipmentList = data
}
mergeLists()
}
function mergeLists() {
mainList = bodypartsList.concat(equipmentList);
displayData(mainList)
}
//bodypart code
const bodyparts = ["Body Parts", "back", "cardio", "chest", "lower arms", "lower legs", "neck", "shoulders", "upper arms", "upper legs", "waist"]
const equipment = ["Equipment", "assisted", "band", "barbell", "body weight", "cable", "dumbbell", "ez barbell", "hammer", "kettlebell", "leverage machine", "medicine ball", "resistance band", "roller", "rope", "smith machine", "tire", "trap bar", "weighted"]
const exercises = document.getElementById("exercises");
window.addEventListener("load", function () {
createDropdown("bodypart", bodyparts);
})
window.addEventListener("load", function () {
createDropdown("equipment", equipment);
})
// const select = document.createElement("select"); //---create the select element
// const option = document.createElement("option"); //---create options for select
function createDropdown(name, items) {
const select = document.createElement("select"); //---create the select element
select.className = "selectMenu"
select.name = name
select.id = name
for (let i = 0; i < items.length; i ) { //---as long as 'i' is less than the number of items increase by 1
const item = items[i]; //---declaring 'i' as items
const option = document.createElement("option"); //---create options for select
option.setAttribute("value", item); //---places item value into options
option.innerHTML = item; //---change content of options to items
select.appendChild(option); //---append options to select
}
exercises.appendChild(select); //---append data to options
select.addEventListener("change", function () {
const item = select.value;
dataDiv.innerHTML = ''; //<------Clears previous results from page
// console.log(item);
getApiURL(name, item);
})
}
function displayData(data) {
// console.log(data);
let d1 = document.getElementById("equipment")
let d2 = document.getElementById("bodypart")
console.log(d2.value);
if (d2.value && d1.value !== -1 ){
const result = data.filter(word => {
return (word.name.indexOf(d1.value))
});
console.log(result);
result.forEach(element => {
const div = document.createElement("div");
const p = document.createElement("p");
// const img = document.createElement("img");
// img.className = "appGifs"
p.innerHTML = element.name
// img.src = element.gifUrl
div.appendChild(p)
// div.appendChild(img)
div.className = "card"
dataDiv.appendChild(div)
});
}
}
HTML
<div class="row-md-6 offset-md-2">
<div class="col-sm-10" style="border:1px solid blue">
Logo goes here
<div class="row">
<div class="col-8 col-sm-6" style="border:1px solid red">
<div id="exercises" class="bg-primary align-items-center"></div> <!--Dropdown Buttons-->
</div>
<div class="col-4 col-sm-6" style="border:1px solid red">
<div id="data"></div> <!--Result Data-->
</div>
</div>
</div>
</div>
<div id="appSubmit"></div> <!--Submit button-->
它目前顯示所有合并的結果,我認為它是將過濾的結果添加到mainList array而不是洗掉不需要的結果。
我真的找不到我做錯了什么并感謝任何幫助
謝謝
uj5u.com熱心網友回復:
您正在混合字串和索引。我還假設您不想像其他發布的答案那樣使用 0 索引進行過濾。
let result = data;
if (d1.selectedIndex > 0) {
const selected = d1.value;
result = result.filter(({equipment}) => equipment.includes(selected));
}
if (d2.selectedIndex > 0) {
const selected = d2.value;
result = result.filter(({bodyPart}) => bodyPart.includes(selected));
}
uj5u.com熱心網友回復:
所以我If I select 'chest' from bodyparts array and 'barbell' from equipment array I only want results with matching values from 'chest' and 'barbell' to appear in the console.從這一行中了解到,如果您從下拉串列中選擇胸部,您希望顯示名稱與所選值匹配的所有資料。
你這樣做:
const result = data.filter(word => {
return (word.name.indexOf(d1.value))
});
indexOf() 方法回傳指定值在字串中第一次出現的位置。如果未找到該值,indexOf() 方法回傳 -1。
它永遠不會回傳您期望的結果。因此,您可以嘗試以下操作,而不是這樣做:
const result = data.filter(word => word.name.includes(d2.value));
這將回傳與 D2 下拉串列的選定值匹配的所有值。對于 d1,您需要執行相同的操作。
更新
用這個改變你的顯示功能
function displayData(data) {
debugger;
// console.log(data);
let d1 = document.getElementById("equipment");
let d2 = document.getElementById("bodypart");
console.log(d2.value);
let value1;
let value2;
//get filtered value for d2
if (d2.value){
value2 = data.filter(word => word.name.includes(d2.value));
}
////get filtered value for d1
if (d1.value){
value1 = data.filter(word => word.name.includes(d1.value));
}
//merge both the value into one using spread operator(... this is called spread operator in JS)
let result = [
...value1,
...value2
];
//loop over the final result
if(result.length > 0){
console.log(result);
debugger;
result.forEach(element => {
debugger;
const div = document.createElement("div");
const p = document.createElement("p");
// const img = document.createElement("img");
// img.className = "appGifs"
p.innerHTML = element.name
// img.src = element.gifUrl
div.appendChild(p)
// div.appendChild(img)
div.className = "card"
dataDiv.appendChild(div)
});
}
}
uj5u.com熱心網友回復:
我認為問題出在你的函式中的 if 條件中 displayData
if (d2.value && d1.value !== -1 ){
const result = data.filter(word => {
return (word.name.indexOf(d1.value))
});
如果d1.valueand之間沒有匹配word.name,則條件回傳-1,而不是0,這意味著即使沒有匹配,它也回傳true(-1表示true,只有0表示false)。
所以你可以簡單地將此條件更改為
return word.name.indexOf(d1.value) !== -1
uj5u.com熱心網友回復:
在 js 中,像陣列和物件這樣的非原語是通過參考傳遞的,所以每當你想比較兩個陣列時,你必須改變資料型別。您必須將物件和陣列更改為字串,然后進行比較。使用 JSON.stringify 來做到這一點。下面的代碼只是一個示例:
const arr1 = []
const arr2 = []
console.log(arr1 === arr2) //false
console.log(JSON.stringify(arr1) === JSON.stringify(arr2)) //true
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359490.html
標籤:javascript 数组 筛选
