Finder of an array of objects with Javascript

3

I have the following code that searches in an array the information that I insert in the input, in this case the code works very well

function autocompletado () {
			document.getElementById("demo").innerHTML = '';

			var preguntame = ["qwe", "ert", "tyu", "uio", "opa", "asd", "fgh", "hjk", "jkl", "xcz", "rt", "sdf"];

		 	var pal = document.getElementById("buscar-pal").value;
		 	var tam = pal.length;
		 	for(indice in preguntame){
				var nombre = preguntame[indice];
				if(pal.length != 0 && nombre.length != 0){
					if(nombre.toLowerCase().search(pal.toLowerCase()) != -1){
						var node = document.createElement("li");
						node.innerHTML = "<a href="+preguntame[0].name+">"+preguntame[indice]+"</a>";
						document.getElementById("demo").appendChild(node);
					}
				}
			}
		}
<input type="text" id="buscar-pal" onkeyup="autocompletado()" style="border: solid 2px">
	<div>
		  <ul id="demo"></ul>
	</div>

but this code clearly does not work for me when I have an array of objects like this

 var preguntame = [
        {nombre: 'manzanas', cantidad: 2},
        {nombre: 'bananas', cantidad: 0},
        {nombre: 'cerezas', cantidad: 5}
    ];

I've been using javascript for a very short time and I have not found a way to search this type of array

I would really appreciate any help.

    
asked by Michael Valdes Gonzalez 07.05.2018 в 18:27
source

1 answer

2

It is very similar to your code. Something like this:

function autocompletado () {
    document.getElementById("demo").innerHTML = '';

	var preguntame = [
        {nombre: 'manzanas', cantidad: 2},
        {nombre: 'bananas', cantidad: 0},
        {nombre: 'cerezas', cantidad: 5}
    ];

	var pal = document.getElementById("buscar-pal").value;
	var tam = pal.length;
	for(indice in preguntame){
	    var item = preguntame[indice];
            var nombre = item.nombre;
	    if(pal.length != 0 && nombre.length != 0){
			if(nombre.toLowerCase().search(pal.toLowerCase()) != -1){
				var node = document.createElement("li");
				node.innerHTML = "<a href="+nombre+">"+nombre+"</a>";
				document.getElementById("demo").appendChild(node);
			}
	    }
	}
}
<input type="text" id="buscar-pal" onkeyup="autocompletado()" style="border: solid 2px">
	<div>
		  <ul id="demo"></ul>
	</div>
    
answered by 07.05.2018 / 18:35
source