简体   繁体   中英

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. 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.

I show you only a part of the Json file:

[
{
    "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:

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({
    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM