gpt4 book ai didi

javascript - 创建 javascript 递归过滤器函数

转载 作者:行者123 更新时间:2023-12-03 11:05:36 24 4
gpt4 key购买 nike

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

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

关于javascript - 创建 javascript 递归过滤器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27871292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com