我目前正在移植我的一个基于 SQL 过滤器的工作应用程序,这样它就不会在每次更改过滤器时都查询数据库,而是从一个单一的 JavaScript 对象数组(“主阵列”)。
// console.log(array)
[Object, Object, Object, ...]
0: Object
date_created: "2014-12-20"
product_id: "1"
product_name: "name"
type: "0"
purchased: "1"
1: Object
date_created: "2014-12-21"
product_id: "2"
product_name: "name2"
type: "1"
purchased: "0"
2: Object
date_created: "2014-12-21"
product_id: "3"
product_name: "name3"
type: "1"
purchased: "0"
... etc etc
目前我有 JavaScript 数组,并且有一个基本的过滤系统,我可以过滤结果以仅显示基本项目(type == 0
),仅显示高级项目( type == 1
),或所有项目。然后,它将根据所选订单按产品名称、成本或添加日期进行排序。
其工作方式是循环遍历主数组,将当前对象分配给变量,然后循环遍历该特定对象。如果设置了仅显示基本 (true
),并且 key == 'type' && value == 0
,那么我们将该对象推送到一个新数组中。在主数组循环结束时,如果新创建的数组仍然为空,则意味着没有匹配。它只是复制主数组,然后对该数组应用一些过滤。
令我头疼且无法理解的是,如何进行多个过滤器?一个对象可能是基本
和购买
,但我当前的算法会将该记录分成两次。就在那时,我考虑计算插入的数量,然后执行 array.splice 删除附加对象,但结果惨遭失败并返回了不需要的结果。这是我的尝试:
function run_filter (type) {
/*ajax_active = true;
$('#loading').show().center();*/
// new empty array
var new_items = [];
// items_length refers to the size of the master array (8 objects in total)
for(var i = 0; i < items_length; i++) {
// grab the current object
var object = all_items[i];
// grab the current size of the new array
var new_items_length = new_items.length;
// reset to 0
var insert_amount = 0;
// for each key in current object
for(var key in object) {
// if show only basic and hide advanced
if (show_basic && !show_advanced) {
if (key == 'type' && object[key] == 0) {
// push the object onto the new array
new_items.push(object);
// incrememnt counter by 1
insert_amount++;
}
}
if (show_advanced && !show_basic) {
if (key == 'type' && object[key] == 1) {
new_items.push(object);
insert_amount++;
}
}
// if we want to hide purchased (i.e. omit records where purchased == 1
if (hide_purchased) {
if (key == 'purchased' && object[key] == 0) {
new_items.push(object);
insert_amount++;
}
}
// if increment counter == 2 or greater (i.e. an object has been inserted twice because it is both basic and hasn't been purchased)
if(insert_amount > 1) {
// new array length BEFORE objects pushed onto new array (+1 to it so that we don't remove the first instance of the object) ; ... < new array length AFTER objects pushed ; increment on loop
for(var index = new_items_length + 1; index < new_items_length + insert_amount; index++) {
// remove the object from the new array at the current index
new_items.splice(index, 1);
}
}
}
}
}
最重要的是,如果一个项目是基本的,被插入新数组,但用户也购买了该记录并将过滤器设置为隐藏购买,该怎么办?它会显示该记录,因为它是基本的,并忽略隐藏购买的过滤器。我知道我可以有数百个嵌套的 if 条件
,但这似乎效率低下......
有什么帮助吗?
最佳答案
我认为您可以使用 Array.filter() 来简化代码它创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。:
function run_filter (type) {
var new_items = all_items.filter(function(obj, index, array) {
// You can do any filter you want here
// Just focus on the filter
return (obj.type == type) && (obj.purchased == "1");
});
return new_items;
}
查看此Example
关于javascript - 对象数组上的多个过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526118/