• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

132
Views
Cómo filtrar una matriz de objetos depende de la entrada en Cambiar texto (Reaccionar)

(Problema de reacción)

Digamos que tenemos una matriz de objetos como este:

 const books = [ { author: "Marcel Proust", title: "In Search of Lost Time", pageNumber: 123, }, { author: "James Joyce", title: "Ulysses", pageNumber: 123, }, { author: "Miguel de Cervantes", title: "Quixote", pageNumber: 123, }, { author: "Herman Melville", title: "Moby Dick", pageNumber: 123, }, { author: "William Shakespeare", title: "Hamlet", pageNumber: 123, }, ];

También tenemos una entrada y un estado como este:

 const [text, setText] = useState(""); const handleOnChange = (event) => { setText(event.target.value); }; <input value={text} onChange={handleOnChange} />;

Ahora, me gustaría filtrar esta matriz según el texto de entrada, y [autor | título] propiedad.

Ejemplo:

Si el usuario escribe 'M', la matriz de objetos debería verse así:

 const books = [ { author: "Marcel Proust", title: "In Search of Lost Time", pageNumber: 123, }, { author: "Miguel de Cervantes", title: "Quixote", pageNumber: 123, }, { author: "Herman Melville", title: "Moby Dick", pageNumber: 123, }, ];

...porque el autor o el título comienzan con la letra M.

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Prueba lo siguiente:

 const filteredBooks = books.filter(book => { return book.title[0] === text || book.author[0] === text; })
about 3 years ago · Juan Pablo Isaza Report

0

Debe usar un filtro en su matriz de books .

 const filtered = books.filter(({author, title}) => author.includes(text) || title.includes(text)

Esto filtrará con su texto en CUALQUIER posición en autor o título. Entonces, en su ejemplo, si escribe "S", tendrá "William Shakespeare". Si desea buscar solo desde el principio, puede usar startsWith en lugar de " includes ".

about 3 years ago · Juan Pablo Isaza Report

0

Pruebe esta función de filtro:

 books.filter(({ author, title }) => author.toLowerCase().includes(text.toLowerCase()) || title.toLowerCase().includes(text.toLowerCase()))
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error