我有:
var data = [
{"a":some_value, "b":some_value},
{"a":some_value, "b":some_value, "c":some_value},
{"a":some_value, "b":some_value},
然后:
var keywords = [
[{key: "a",value: 1}],
[{key: "b",value: 1},{key: "b",value: 2}]
];
所以我需要找到数据有((a = 1)AND(b = 1或b = 2)):
filteredData = $.grep(data, function (value, i) {
if (value[keywords[0][0].key] !== keywords[0][0].value) return false;
if (value[keywords[1][0].key] !== keywords[1][0].value) && (value[keywords[1][1].key] !== keywords[1][1].value)return false;
return true;
});
一切都很好,但现在我需要动态数据,关键字,我不能这样做!
答案 0 :(得分:3)
尝试
var array = $.grep(data, function(obj, idx){
return keywords.every(function(list, idx, src){
return list.some(function(item, idx, src){
return obj[item.key] == item.value
});
});
});
console.log(array)
演示:Fiddle
对于IE< 9支持,您可能必须包括
的pollyfills答案 1 :(得分:0)
filteredData = $.grep(data, function(value, i) {
for (var k = 0; k < keywords.length; k++) {
var matched = false;
var orlist = keywords[k];
for (var l = 0; l < orlist.length; l++) {
if (value[orlist[l].key] == orlist[l].value) {
matched = true;
break;
}
if (!matched) {
return false;
}
}
return true;
});
答案 2 :(得分:0)
jQuery很棒,但它不是所有内容的答案,对于这个特定的情况,它可以简单地完成,只需要很好的'纯粹的Javascript:
var data = [
{"a":1, "b":100},
{"a":1, "b":2, "c":3},
{"a":2, "b":10}
];
var keywords = [
[{key: "a",value: 1}],
[{key: "b",value: 1},{key: "b",value: 2}]
];
function filter(data, keywords) {
var ret = [];
for(var i = 0, d, m; i < data.length; ++i) {
d = data[i];
m = true;
for(var x = 0; x < keywords.length && m; ++x) {
for(var k = 0; k < keywords[x].length && m; ++k) {
var rule = keywords[x][k];
console.log(d, d[rule.key] === rule.value, rule);
m = m && rule.key in d && d[rule.key] === rule.value;
}
if(m) break;
}
if(m) ret.push(d);
}
return ret;
}
console.log(filter(data, keywords));
这是es5版本,没有jQuery(可以与旧版浏览器的es5-shim一起使用):
function es5_grep(data, keywords) {
return data.map(function(row) {
return keywords.every(function(list){
return list.some(function(item){
return row[item.key] === item.value
});
}) ? null : row;
}).filter(function(v) { return !!v; });
}
这仅供将来参考,https://stackoverflow.com/a/22512882/145587是使用jQuery的正确答案。