1
我正在嘗試使用React JS創建搜索。通過陣列與另一個陣列進行過濾
我有一個數組(汽車),我想通過它搜索。我有一個過濾器陣列(在這種情況下是一個),我需要應用。最後,我擁有該過濾器的內容。
我有這樣三個數組對象:
汽車(全車的列表)。它看起來如下:
let cars = [ {"id":20,"listID":3,"make":"Golf"}, {"id":21,"listID":3,"make":"Passat"}, {"id":22,"listID":3,"make":"Audi"}, {"id":23,"listID":3,"make":"Touran"}, {"id":24,"listID":3,"make":"Touran"} ];
過濾器(陣列的所有過濾器 - 在這種情況下,只有一個過濾器):
let filters = [ {"name":"FAVORITES","values":[ {"carID":21,"listID":3,"userID":12}, {"carID":22,"listID":3,"userID":12} ] } ];
夾(即過濾器的內容):
let favorites = [ {"carID":21,"listID":3,"userID":12}, {"carID":22,"listID":3,"userID":12} ];
渲染功能如下:
render(){
return cars.filter(car => filters.every(filter => filterItem(filter, car)))
}
因此,我過濾所有的汽車,應用每個過濾器,然後調用每個汽車和每個過濾器的filterItem函數。
和功能的FilterItem(這裏我想要得到的結果)如下:
function filterItem(filter, car) {
switch(filter.name) {
case "FAVORITES":
return filter.values.map(f => f).every(v => car.id === v.carID && car.listID === v.listID);
default:
return true;
}
}
這一切都在一個部件結合:
let favorites = [
{"carID":21,"listID":3,"userID":12},
{"carID":22,"listID":3,"userID":12}
];
let cars = [
{"id":20,"listID":3,"make":"Golf"},
{"id":21,"listID":3,"make":"Passat"},
{"id":22,"listID":3,"make":"Audi"},
{"id":23,"listID":3,"make":"Touran"},
{"id":24,"listID":3,"make":"Touran"}
];
let filters = [
{"name":"FAVORITES","values":[
{"carID":21,"listID":3,"userID":12},
{"carID":22,"listID":3,"userID":12}
]
}
]
function filterItem(filter, car) {
switch(filter.name) {
case "FAVORITES":
return filter.values.map(f => f).every(v => car.id === v.carID && car.listID === v.listID);
default:
return true;
}
}
class Test extends React.Component {
render(){
return (
<div>
{cars.filter(car => filters.every(filter => filterItem(filter, car)))}
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
因此我想通過汽車搜索,並應用所有過濾器(在這種情況下只有一個)並獲得結果。
因此,在這種情況下,結果應該是:
let results = [
{"id":21,"listID":3,"make":"Passat"},
{"id":22,"listID":3,"make":"Audi"}
]
但是我的代碼我什麼也沒得到。
有什麼建議嗎?
我解決它了。這就是解決方案。 :) , 不管怎麼說,還是要謝謝你。 – Boky