0

I have info like this inside an array-

{codigo: "", clave: "USB005", nombre: "memoria usb kingston 16 GB", precio: "165", stock: "0"}

{codigo: "", clave: "USB001", nombre: "MEMORIA USB BLACKPCS 16 GB", precio: "165", stock: "0"}

{codigo: "", clave: "USB003", nombre: "MEMORIA USB SP 16 GB", precio: "165", stock: "0"}

And I have a textfield for searching specific data, for now it works with the key codigo and clave but I would like to make it work with nombre as well but in this case is different because if I write "Memoria" it should get the values the matches the word but I have no idea how to achieve this, I tried with indexOf but it doesn't work as I thought

This is how I did with codigo and clave

$.each(todos, function(i) {

    if (busqueda == todos[i]['clave'] || busqueda == todos[i]['codigo']) {

        $('#resultado_precio').html(
            `<h4 class="text-danger m-t-25"><b>Precio: $ ${decimales(todos[i]['precio'])}</b></h4>
            <h4 class="text-danger"><b>${todos[i]['nombre']}</b></h4>
            <h4 class="text-danger"><b>Stock: ${todos[i]['stock']}</b></h4>`
        );

        return;

 }

});

How can make to find the first 5 matches of the word I write to search in the key nombre?

I hope you can help me with some ideas, thanks.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ashe
  • 187
  • 1
  • 13

1 Answers1

0

You can use indexOf() with OR (||) condition like below:-

Working example:-

var todos = [{codigo: "", clave: "USB005", nombre: "memoria usb kingston 16 GB", precio: "165", stock: "0"},{codigo: "", clave: "USB001", nombre: "MEMORIA USB BLACKPCS 16 GB", precio: "165", stock: "0"},{codigo: "", clave: "USB003", nombre: "MEMORIA USB SP 16 GB", precio: "165", stock: "0"}];

var busqueda = "memoria";
$.each(todos, function(i) {

  if (busqueda == todos[i]['clave'] || busqueda == todos[i]['codigo'] || todos[i]['nombre'].toUpperCase().indexOf(busqueda.toUpperCase()) !==-1) {

    alert('found');

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note:- you can use toLowerCase() also

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98