创建一个javascript递归过滤器函数

时间:2015-01-10 00:06:48

标签: javascript recursion

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

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

2 个答案:

答案 0 :(得分:1)

它不需要递归(我不确定你理解这意味着什么),你只需要循环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));

答案 1 :(得分:0)

试试这段代码:

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