Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
Función de búsqueda de un valor en una matriz de objetos

He intentado crear una función que busque el título en una matriz de objetos de libros. Por alguna razón, mi código no funciona, he intentado seguir cada paso lógicamente y, en mi opinión, debería funcionar.

 let book = { title: "The 48 Laws of Power", author: "Robert Greene", numOfPages: 452, publisher: "Penguin Books", rating: "4.5 stars" } let book2 = { title: "How to Catch a Turkey", author: "Adam Wallace", numOfPages: 40, publisher: "", rating: "5 stars" } let book3 = { title: "Glitter Every Day: 365 Quotes from Women I Love", author: "Andy Cohen", numOfPages: 384, publisher: "Henry Holt and Co.", rating: "3 stars" } let bookArr = [book, book2, book3]; let searchBtn = document.getElementById('search-button'); let found = false; let bookSearch = function() { found = false; let input = document.getElementById('book-search'); for (i = 0; i < bookArr.length; i++) { if (input.value.toLowerCase == bookArr[i].title.toLowerCase) { found = true; break; } } if (found) { console.log(bookArr[i]); } else { console.log("The book was not found."); } } searchBtn.addEventListener('click', bookSearch);
 <input type="text" id="book-search" placeholder="Search books..."> <button id="search-button">Search</button> <script src="object.js"></script>

Y, por último, soy nuevo en este foro y también nuevo en la programación, así que pido disculpas si esta es la forma incorrecta de hacer preguntas, pero realmente agradecería algunas críticas sobre mi código y lo que debería hacer mejor. ¡Gracias!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puedes usar Array.find() y es tan fácil como:

 var book = bookArr.find(book => book.title.toLowerCase() == input.value.toLowerCase())

Demostración de trabajo

 let book = { title: "The 48 Laws of Power", author: "Robert Greene", numOfPages: 452, publisher: "Penguin Books", rating: "4.5 stars" } let book2 = { title: "How to Catch a Turkey", author: "Adam Wallace", numOfPages: 40, publisher: "", rating: "5 stars" } let book3 = { title: "Glitter Every Day: 365 Quotes from Women I Love", author: "Andy Cohen", numOfPages: 384, publisher: "Henry Holt and Co.", rating: "3 stars" } let bookArr = [book, book2, book3]; let searchBtn = document.getElementById('search-button'); let found = false; let bookSearch = function() { let input = document.getElementById('book-search'); var book = bookArr.find(book => book.title.toLowerCase() == input.value.toLowerCase()) if (book) { console.log(book); } else { console.log("The book was not found."); } } searchBtn.addEventListener('click', bookSearch);
 <input type="text" id="book-search" placeholder="Search books..."> <button id="search-button">Search</button> <script src="object.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Si solo desea la primera coincidencia, use Array.find().

 books.find(book => book.title == 'mysearch');

Si desea una matriz de coincidencias, use Array.filter().

 books.filter(book => book.title == 'mysearch');

Si está utilizando Typescript, puede agregar seguridad de tipo y hacer que la función de búsqueda sea más fácil de usar.

 function search<Type, Key extends keyof Type>(arr: Type[], prop: Key, match: Type[Key]){ // For a single item return arr.find(item => item[prop] == match); // For an array of matches return arr.filter(item => item[prop] == match); }

Luego creamos una interfaz para un libro y podemos buscarlo fácilmente mientras se autocompleta.

 interface Book { title: string; author: string; numOfPages: number; publisher: string rating: string; } search(books, "title", "Harry Potter")

Aquí hay un patio de juegos de TS para probar el código usted mismo. Enlace

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda