创建一个 javascript 递归过滤函数

creating a javascript recursive filter function

有没有办法使这个函数递归,这样我就不需要为每个长度的过滤条件创建一个开关?

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));

不需要递归(我不确定你明白什么意思),你只需要循环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));

试试这个代码:

function select(data, where) {
    return data.filter(function (e) {
        for (var key in where) {
            if (where.hasOwnProperty(key)) {
                if (e.hasOwnProperty(key)) {
                    if (e[key] != where[key]) {
                        return false;
                    }
                }
                else {
                    return false
                }
            }
        }

        return true;
    })
}