Estoy tratando de filtrar la matriz de objetos según el valor seleccionado por el usuario de la lista desplegable
Como puede ver en el siguiente ejemplo, quiero filtrar la matriz en función de la chain
y officeid
. Si uno de ellos está vacío, quiero omitir ese filtro.
let list = [{ "index": 4, "chain": "aaa", "officeId": "bbb" }, { "index": 5, "chain": "ccc", "officeId": "ddd" }]; function search(chain, office) { let data = list.filter(function(result) { return result.chain === chain && result.officeId === office; }); console.log(data); } search('aaa','bbb'); // this will work fine search('aaa',''); // this returns empty array search('', 'bbb'); // empty array
En las 3 declaraciones anteriores, espero el mismo resultado para todos
Si ambos están vacíos, debe omitir el filtro y devolver la matriz original
es decir search('', '');
no debe aplicar ningun filtro
intente usar esto en su lugar, solo tiene que agregar una condición más
let list = [{ "index": 4, "chain": "aaa", "officeId": "bbb" }, { "index": 5, "chain": "ccc", "officeId": "ddd" }]; function search(chain, office) { let data = list.filter(function(result) { if( result.chain === chain && result.officeId === office){ return result } if(!chain && !office){ return result; } }); console.log(data); } search('aaa','bbb'); // this will work fine search('aaa',''); // this returns empty array search('', 'bbb'); // empty array search("","");
También puedes usar una mano corta como esta
let data = list.filter(function(result) { return (!chain && !office) || (result.chain === chain && result.officeId === office); });