Tengo los siguientes objetos. Quiero filtrarlos en javascript y obtener todos los objetos con el nombre de área de "Vibestuen".
[ { "id": 292, "name": "Hans", "image": "as", "calculatedVacation": 1.0, "area": { "name": "Ikke tilknyttet en stue" } }, { "id": 295, "name": "xx", "image": "zz", "calculatedVacation": 2.0, "area": { "name": "Vibestuen" } }, { "id": 296, "name": "xx", "image": "abccc.png", "calculatedVacation": 2.0, "area": { "name": "Andestuen" } }, { "id": 298, "name": "bunun", "image": "zz", "calculatedVacation": 2.0, "area": null }, { "id": 299, "name": "lort", "image": "kol", "calculatedVacation": 2.0, "area": { "name": "Vibestuen" } } ]Actualmente mi javascript se ve de la siguiente manera:
fetch(baseURL + "/employees") .then(response => response.json()) .then(result => { let vibeEmployees = result.filter(employee => employee.includes('Vibestuen')); console.log(vibeEmployees) })Recibo el siguiente error:
Uncaught (in promise) TypeError: employee.includes is not a function at showEmployeeVibe.js:4 at Array.filter (<anonymous>) at showEmployeeVibe.js:4¿Cómo filtro estos objetos?
incluye verificar si el parámetro está contenido en Array. Tu filtro debería verse así
result.filter(employee => employee.area && employee.area.name === 'Vibestuen')Puedes hacerlo así:
let vibeEmployee = result.filter(employee => employee.area && employee.area.name === 'Vibestuen')Necesita cambiar la condición dentro de la función de devolución de llamada del filtro. empleado representa un objeto y el área es nula en pocos registros.
Ejemplo: let vibeEmployees = data.filter( (employee) => employee.area && employee.area.name.includes("Vibestuen") );