(使用 react js)我正在嘗試過濾這個陣列:
[
{gov:"A1", district:"1" , town:"t1", type:"cars factory"},
{gov:"A2", district:"2" , town:"t2", type:"farm"},
{gov:"A1", district:"1" , town:"t1", type:"milk factory"},
{gov:"A1", district:"4" , town:"t3", type:"milk factory"},
{gov:"A3", district:"3" , town:"t4", type:"medicine factory"},
{gov:"A4", district:"6" , town:"t5", type:"food"},
{gov:"A3", district:"7" , town:"t4", type:"milk factory"},
{gov:"A2", district:"2" , town:"t7", type:"construction"},
]
假設這個陣列稱為 Locations,我需要實作 4 個過濾器,第一個過濾器是使用 gov (governates) 過濾,第二個過濾器使用 Districts ,第三個使用城鎮,最后使用行業型別。但是如果我已經選擇了按地區過濾,那么我想過濾該地區內的行業型別,我需要動態進行;這樣,我實作了 4 個選擇輸入(政府、地區、城鎮、型別),我可以一直過濾原始陣列,但這將始終回傳例如所有政府中的牛奶工廠,而不是特定的政府。所以我需要的是根據多個屬性或屬性進行過濾,而不僅僅是靜態撰寫
newArray=Locations.filter( (e)=>{ return e.gov=='A1' && e.type='milk factory'})
這解決了它,但并非總是如此,因為我也可能選擇在特定地區、城鎮甚至整個國家(在父陣列上)過濾牛奶工廠
讓我們假設
gov \\is the value of the selection of governorates
district \\is the value of the selection of districts
town \\is the value of the selection of towns
type \\is the value of the selection of the type
順便說一句,我正在使用反應傳單地圖在標記上顯示這些值,這就是我需要過濾的原因。
所以我想把它貼在這里,也許好心人會幫我解決這個問題謝謝你們
uj5u.com熱心網友回復:
您可以使用以下方法。這個想法是將所有過濾器放在一個匹配的物件中,然后在filterData您更改時呼叫matchObj:)
const data = [
{gov:"A1", district:"1" , town:"t1", type:"cars factory"},
{gov:"A2", district:"2" , town:"t2", type:"farm"},
{gov:"A1", district:"1" , town:"t1", type:"milk factory"},
{gov:"A1", district:"4" , town:"t3", type:"milk factory"},
{gov:"A3", district:"3" , town:"t4", type:"medicine factory"},
{gov:"A4", district:"6" , town:"t5", type:"food"},
{gov:"A3", district:"7" , town:"t4", type:"milk factory"},
{gov:"A2", district:"2" , town:"t7", type:"construction"},
];
const filterData = (matchObj) => {
const matchEntries = Object.entries(matchObj);
return data.filter(item => {
return matchEntries.every(([key, val]) => item[key] === val);
});
};
// Tests:
const matchObj1 = { gov:"A1" };
console.log(matchObj1, filterData(matchObj1));
const matchObj2 = { gov:"A1", type: "milk factory" };
console.log(matchObj2, filterData(matchObj2));
const matchObj3 = { gov:"A1", type: "milk factory", town: "t3" };
console.log(matchObj3, filterData(matchObj3));
uj5u.com熱心網友回復:
我認為您可以使用此代碼示例之類的標準來實作您的過濾器
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397318.html
標籤:javascript 数组 反应 搜索 过滤
上一篇:添加條件值的Python字典創建
下一篇:發現nil時將默認值添加到陣列
