[英]How to create a search filter from Json in Javascript
I have been learning Javascript for a short time and in order to assimilate the knowledge I am acquiring, I am carrying out an e-commerce project.我学习 Javascript 的时间很短,为了吸收我所获得的知识,我正在开展一个电子商务项目。 I want to create a search filter from an input, so that it shows me only the products that the user wants, I want to read this from a .Json file that has all the products.
我想从输入中创建一个搜索过滤器,以便它只向我显示用户想要的产品,我想从包含所有产品的 .Json 文件中读取它。
I show you only a part of the Json file:我只向您展示 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"
}
]
I call this to Js via a fetch:我通过 fetch 将其称为 Js:
const fetchData = async() => {
try{
const res = await fetch("./productos.json");
const data = await res.json();
} catch(error){
console.log(error);
}
}
What I want to know is how I can make it so that every time the user searches for something, only those products appear on the screen,thanks for reading.我想知道的是我怎样才能做到,每次用户搜索某些东西时,屏幕上只会出现那些产品,感谢阅读。
You can use ajax to get the JSON file and select the specific field you want.您可以使用 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
}
});
You can easily apply a filter on your "data" array based on what the user has searched.您可以根据用户搜索的内容轻松地对“数据”数组应用过滤器。 Assuming the user will search by title you can do something like:
假设用户将按标题搜索,您可以执行以下操作:
const selectedData = data.filter((item) => item.title.indexof("search text") > -1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.