To solve specifically the problem shown, this is the solution I found:
const escuelas = [
{id_escolares_pk: 1,escuela: "Gregorio",tipo: "Pública",id_nivel_fk: 1},
{id_escolares_pk: 2,escuela: "Ignacio",tipo: "Privada",id_nivel_fk: 1},
{id_escolares_pk: 3,escuela: "UTZ",tipo: "Pública",id_nivel_fk: 1}
];
// Arreglo con las condiciones a ejecutar
const listaCondiciones = [
{ columna: "id_nivel_fk", valor: 1, operador: "===" },
{ columna: "tipo", valor: "Pública", operador: "!==" }
];
// Ejecución de filter
const encontrados = escuelas.filter(elemento => cumpleLasCondiciones(elemento, listaCondiciones));
// Verifica todas las condiciones para el elemento dado
function cumpleLasCondiciones(elemento, condiciones) {
return !condiciones
.map(condicion => evaluarCondicion(elemento, condicion))
.includes(false);
}
function evaluarCondicion(elemento, condicion) {
if(condicion.operador === "===")
return elemento[condicion.columna] === condicion.valor;
if(condicion.operador === "!==")
return elemento[condicion.columna] !== condicion.valor;
if(condicion.operador === "==")
return elemento[condicion.columna] == condicion.valor;
if(condicion.operador === "!=")
return elemento[condicion.columna] != condicion.valor;
if(condicion.operador === "<")
return elemento[condicion.columna] < condicion.valor;
if(condicion.operador === "<=")
return elemento[condicion.columna] <= condicion.valor;
if(condicion.operador === ">")
return elemento[condicion.columna] > condicion.valor;
if(condicion.operador === ">=")
return elemento[condicion.columna] >= condicion.valor;
}
console.log(encontrados);
In cumpleLasCondiciones
is where the magic happens.
map(condicion => elemento[condicion.columna] === condicion.valor)
executes each check and returns true
or false
depending on whether it complies or not.
The resulting arrangement consists of the results of these evaluations, so we look for if some were not met with includes(false)
.
Finally, if one was found that was not fulfilled ( includes
returns true
), we deny the value with !condiciones
, which in the end is used by the escuelas.filter
to know if the element passes or not .
To add more operators, you can use the Orlando method, adding one more property to the comparisons object and creating a function to apply in map
.