crankshaft crankshaft - 4 months ago 33
Javascript Question

creating a javascript recursive filter function

Is there any way of making this function recursive so that I do not need to create a switch for each length of filter criteria ?

var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]


function select(data,where){
return data.filter(function(e){
var k = Object.keys(where);
switch(k.length){
case 1: return (e[k[0]] == where[k[0]]);
case 2: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]]);
case 3: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]]);
case 4: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]]);
case 5: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]] && e[k[4]] == where[k[4]]);
}
})
}

var where = {a:'aaa',b:'bbb'}

console.log(select(data,where));

Answer

It doesn't need to be recursive (I'm not sure you understand what that means), you just need to loop on the elements in where:

function select(data, where) {
  return data.filter(function(e) {
    var k = Object.keys(where);
    return k.every(function(key) {
      return e[key] == where[key];
    });
  })
}

var data = [
  {a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
  {a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
  {a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]

var where = {a:'aaa',b:'bbb'}

console.log(select(data,where));

Comments