我正在尝试使用对象的二维过滤器数组来过滤对象的数据数组。
我的数据数组看起来像这样:
dataArray = [{
Filter_GroupSize: "1"
Filter_Time: "5-30"
title: "Tools Test 1"
}, {
Filter_GroupSize: "5-10"
Filter_Time: "60-120"
title: "Tools test 2"
}, {
Filter_GroupSize: "5-10"
Filter_Time: "120-240"
title: "Tools 3"
}, {
Filter_GroupSize: "10-20"
Filter_Time: "240-360"
title: "Tools Test 4"
}]问题是,二维滤波器阵列可以随着时间的推移而变化。在我下面的例子中,它的长度是2,但随着时间的推移,它可以变大或变小。如果2D滤波器阵列改变,则dataArray也改变。
这是我的对象的二维过滤器数组现在的样子。
FiltersToApply = [
[{
choice: "5-10"
internalColName: "Filter_GroupSize"
}, {
choice: "10-20"
internalColName: "Filter_GroupSize"
}],
[{
choice: "60-120"
internalColName: "Filter_Time"
}, {
choice: "120-240"
internalColName: "Filter_Time"
}]
]我想过滤整个数据数组,只返回2D过滤器数组中同时具有"Filter_GroupSize“和"Filter_Time”值的元素。在本例中,我希望在一个新的数组中返回"Tools test 2“和"Tools 3”元素。我想要一个筛选器函数来检查"FiltersToApply“,如果它找到匹配,它就检查"FiltersToApply1”是否与dataArray中的相同元素匹配。
我已经带着代码走了这么远:
for (let i = 0; i < FiltersToApply.length; i++) {
console.log(FiltersToApply[i]);
FiltersToApply[i].forEach((filter) => {
var filteredArray: Tool[] = dataArray.filter((item) => {
if (item[filter.internalColName] == filter.choice && ((i+1) <= FiltersToApply.length)) {
this.nextArray(FiltersToApply[i+1], item);
}
});
});
}但我被困在这里了。谁有好的解决方案?
发布于 2019-12-02 18:45:17
我让它在下面的代码片段中工作,基本上是扁平化过滤器数组,并使用属性名称对它们进行分组,然后对其进行过滤。
var dataArray = [{
Filter_GroupSize: "1",
Filter_Time: "5-30",
title: "Tools Test 1"
}, {
Filter_GroupSize: "5-10",
Filter_Time: "60-120",
title: "Tools test 2"
}, {
Filter_GroupSize: "5-10",
Filter_Time: "120-240",
title: "Tools 3"
}, {
Filter_GroupSize: "10-20",
Filter_Time: "240-360",
title: "Tools Test 4"
}];
var FiltersToApply = [
[{
choice: "5-10",
internalColName: "Filter_GroupSize"
}, {
choice: "10-20",
internalColName: "Filter_GroupSize"
}],
[{
choice: "60-120",
internalColName: "Filter_Time"
}, {
choice: "120-240",
internalColName: "Filter_Time"
}]
];
// flat the filter array to get a linear format, then group by properties to combine choices
var filterArr = FiltersToApply.flat().reduce(function (a, cv) {
(a[cv.internalColName] = a[cv.internalColName] || []).push(cv.choice);
return a;
}, []);
var result = dataArray.filter(function(v){
return filterArr.Filter_GroupSize.indexOf(v.Filter_GroupSize) > -1 && filterArr.Filter_Time.indexOf(v.Filter_Time) > -1
});
console.log(result.map(function(v){ return v.title; }))
https://stackoverflow.com/questions/59136659
复制相似问题