![](/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.