![](/img/trans.png)
[英]How to create search bar for name search json javascript using filter
[英]How to create a search filter from Json in Javascript
我學習 Javascript 的時間很短,為了吸收我所獲得的知識,我正在開展一個電子商務項目。 我想從輸入中創建一個搜索過濾器,以便它只向我顯示用戶想要的產品,我想從包含所有產品的 .Json 文件中讀取它。
我只向您展示 Json 文件的一部分:
[
{
"id": 1,
"title": "Intel Core i5 11400",
"price": 28190,
"imageUrl": "../images/productos/procesadores/intel-2.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 2,
"title": "Intel Core i5 11400F",
"price": 22210,
"imageUrl": "../images/productos/procesadores/intel-1.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 3,
"title": " Intel Core i5 11600KF",
"price": 33650,
"imageUrl": "../images/productos/procesadores/intel-2.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 4,
"title": "Intel Core i5 12400",
"price": 37068,
"imageUrl": "../images/productos/procesadores/intel-6.jpg",
"description": "Socket 1700 12th Gen"
},
{
"id": 5,
"title": "Intel Core i7 11700K",
"price": 55009,
"imageUrl": "../images/productos/procesadores/intel-3.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
}
]
我通過 fetch 將其稱為 Js:
const fetchData = async() => {
try{
const res = await fetch("./productos.json");
const data = await res.json();
} catch(error){
console.log(error);
}
}
我想知道的是我怎樣才能做到,每次用戶搜索某些東西時,屏幕上只會出現那些產品,感謝閱讀。
您可以使用 ajax 獲取 JSON 文件並選擇所需的特定字段。
$.ajax({
type: "GET",
url: "processor.json",
dataType: "json",
async: false,
success: function(response) {
var title = response.title;
var price = response.price;
console.log(title);
console.log(price);
// And so on with the others fields
}
});
您可以根據用戶搜索的內容輕松地對“數據”數組應用過濾器。 假設用戶將按標題搜索,您可以執行以下操作:
const selectedData = data.filter((item) => item.title.indexof("search text") > -1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.