数组中的Javascript嵌套过滤器 [英] Javascript nested filters in Array of arrays
问题描述
我有以下格式的对象数组:
I have an array of objects in this format:
var full_list = [
{
"pid": 1,
"items":[
{"item_id": '9'},
{"item_id": '10'},
{"item_id": '12'}
]
},
{
"pid": 2,
"items":[
{"item_id": '33'},
{"item_id": '22'},
{"item_id": '65'}
]
}...
];
我有一个tmp数组,其中包含来自整个数组的对象:
I have a tmp array which consists of objects from the full array:
var tmp_list = [
{
"pid": 2,
"items":[
{"item_id": '33'},
{"item_id": '22'},
{"item_id": '65'}
]
}, {....}
我想从整个列表中过滤掉对象,其中至少一个selectedIDs值出现在对象的项目ID数组中
I would like to filter out objects from the full list where at least one of selectedIDs values appears in the object's item's id array
var selectedIDs = {'1', '9', '45', ....};
,然后将它们添加到tmp列表中.
and then add them to the tmp list.
我尝试使用过滤器,但无法完全弄清.
I tried using filters but I failed to figure it out completely.
谢谢.
selectedIDs.forEach(function(id) {
var tmp = full_list.filter(function (obj) {
obj.items.forEach(function (item) {
if (item.id === id) {
console.log('found');
}
});
});
tmp_list.push(tmp);
});
推荐答案
首先,您问题中的这一行是错误的
First of all, this line in your question is wrong
var selectedIDs = {'1','9','45',....};
var selectedIDs = {'1', '9', '45', ....};
您不能使用 {}
声明数组.而是使用 []
You cannot declare arrays using {}
. Instead use []
对于您的问题,您可以使用纯功能方法,并使用 Array#filter 和 Array#some 方法来获得所需的结果,如下所示:
For your problem you can use a pure functional approach using Array#filter and Array#some methods to get your desired result as below:
var full_list = [
{
"pid": 1,
"items":[
{"item_id": '9'},
{"item_id": '10'},
{"item_id": '12'}
]
},
{
"pid": 2,
"items":[
{"item_id": '33'},
{"item_id": '22'},
{"item_id": '67'}
]
},
{
"pid": 9,
"items":[
{"item_id": '33'},
{"item_id": '22'},
{"item_id": '65'}
]
},
{
"pid": 7,
"items":[
{"item_id": '7'},
{"item_id": '22'},
{"item_id": '65'}
]
}
];
var tmp_list = [
{
"pid": 2,
"items":[
{"item_id": '7'},
{"item_id": '22'},
{"item_id": '65'}
]
}
];
function filterResult (selectedItems) {
return full_list.filter(function (process) {
return process.items.some(function(item){
return selectedItems.indexOf(item.item_id) > -1;
});
});
}
var selectedItems = ['9', '7', '22', '10'];
tmp_list = tmp_list.concat(filterResult(selectedItems))
console.log(tmp_list);
function flattenResults(list, selections) {
return list.reduce(function (accumulator, current) {
var res = current.items.filter(function(item){
return (selections.indexOf(item.item_id) > -1
&& checkIfAlreadyExist());
function checkIfAlreadyExist () {
return accumulator.every(function (k) {
return k.item_id !== item.item_id;
});
}
});
return accumulator.concat(res);
}, []);
}
console.log(flattenResults(full_list, selectedItems));
这篇关于数组中的Javascript嵌套过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!