Home > Net >  How to create a search filter from Json in Javascript
How to create a search filter from Json in Javascript

Time:06-21

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.

CodePudding user response:

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

CodePudding user response:

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
    }
});
  • Related