如何在Javascript中从Json创建搜索过滤器



我学习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调用它:

const fetchData = async() => {
try{
const res = await fetch("./productos.json");
const data = await res.json();   
} catch(error){
console.log(error);
}
}

我想知道的是我如何才能使它,所以每次用户搜索的东西,只有这些产品出现在屏幕上,感谢阅读。

你可以很容易地对你的"数据";基于用户搜索内容的数组。假设用户将按标题搜索,您可以这样做:

const selectedData = data.filter((item) => item.title.indexof("search text") > -1);

您可以使用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
}
});

最新更新