reduce - 复杂的 .reduce 过滤数组
问题描述
所以我正在尝试编写一个花哨的reduce函数(我可以循环,但是......)。希望对此有所帮助-
初始items
数组:
const items = [
{'labels': ['a'], 'team': "infra"},
{'labels': [], 'team': "infra"},
{'labels': [], 'team': "InfraNew"},
{'labels': ['new'], 'team': "infrastructure org"},
{'labels': ['aaa'],'team': "infra"},
{'labels': [], 'team': "Infra 1"},
{'labels': ['b'],'team': "infra"},
{'labels': ['a'],'team': "DT"},
{'labels': ['c'], 'team': "DT"},
{'labels': ['c', 'b'], 'team': null}
]
和filters
对象。
const filters = {
team: ['infra', 'DT'],
labels: ['a', 'b']
}
目标是results
在过滤后的团队中获取带有标签的项目数组。(因此,如果团队没有匹配的标签,则应将其排除)。
const results = [
{'labels': ['a'],'team': "infra"},
{'labels': ['b'],'team': "infra"},
{'labels': ['a'],'team': "DT"},
]
这就是我所拥有的,但似乎无法正确调节。
function filtering(res, el) {
for (let i = 0; i < Object.keys(filters).length; i++) {
const key = Object.keys(filters)[i];
let filterArray = filters[key];
const elementValue = el[key];
if (!elementValue) return res;
if (key === 'labels') {
if (elementValue.length === 0) return res;
elementValue.map(elementValueItem => {
if (filterArray.indexOf(elementValueItem) < 0) {
return res
}
})
} else if (filterArray.indexOf(elementValue) < 0) {
return res;
}
}
res.push(el);
return res;
}
var results = items.reduce(filtering, [])
console.log(results)
这是jsfiddle
解决方案
如果您从Array.prototype.filter
. 我在下面为你做了
const items = [
{'labels': ['a'], 'team': "infra"},
{'labels': [], 'team': "infra"},
{'labels': [], 'team': "InfraNew"},
{'labels': ['new'], 'team': "infrastructure org"},
{'labels': ['aaa'],'team': "infra"},
{'labels': [], 'team': "Infra 1"},
{'labels': ['b'],'team': "infra"},
{'labels': ['a'],'team': "DT"},
{'labels': ['c'], 'team': "DT"},
{'labels': ['c', 'b'], 'team': null},
]
const filters = {
team: ['infra', 'DT'],
labels: ['a', 'b'],
}
const shouldKeep = item => {
if (!filters.team.includes(item.team)) {
return false
}
if (item.labels.length === 0) {
return false
}
for (const label of item.labels) {
if (!filters.labels.includes(label)) {
return false
}
}
return true
}
console.log(
items.filter(shouldKeep)
)
推荐阅读
- qt - 对于 QBS,我将在我的 DynamicLibrary{} 中设置哪些参数以在构建时安装标头和库?
- java - Android Studio 程序在用户登录时崩溃
- python - Pandas.get_dummies() 单列编码
- ruby - 并行 gem Ruby 中的线程
- symfony - 防止在 symfony 中自动加载抽象控制器
- reactjs - 每次在 React JS 中调整浏览器大小时都会调用 ComponentDidMount
- r - 日期不在 X 轴上
- instagram-api - 获取相关的 Instagram 标签
- python - Pandas 循环优化
- java - 使用 Jsoup 获取内容的跨度