我正在编写一个基于多个条件的JSON数组过滤函数。
过滤器依赖于两个数组: 1.第一个数组包含的值必须是搜索到的JSON的一部分,2.第二个数组包含可选的值。
我的意思是只返回包含obligatory
数组中的所有值和optional
数组中至少一项的数组条目。
这是我的尝试:
const searchKeys = ['varWord', 'varTrans', 'varSpec'],
obligatory = ['trip', 'pret'],
optional = ['greet', 'lco', 'toto', 'bene'];
function filterByUpdate(obligatory, optional, file) {
return _.filter(file, item => {
return _.some(optional, opt => {
return _.every(obligatory, oblg => {
return _.some(item, value => {
return _.some(searchKeys, n => item[n].toLowerCase().includes(oblg.toLowerCase())) &&
searchKeys.some(n => item[n].toLowerCase().includes(opt.toLowerCase()))
})
});
});
});
}
上面的代码应该只保留以下数据数组中的第一个条目:
[{
"varSpec": "trip",
"varTrans": "pret",
"varWord": "greet",
"stringPol": "group",
"stringDva": "groupGend",
"stringGit": "/tax",
}, {
"varSpec": "trip",
"varTrans": "pret",
"varWord": "friend",
"stringPol": "N",
"stringDva": "N",
"stringGit": "N",
}, {
"varSpec": "group1",
"varTrans": "grp1",
"varWord": "ageGroup1",
"stringPol": "N",
"stringDva": "N",
"stringGit": "N",
}]
发布于 2018-09-24 01:28:28
你可以使用这个非常简单的算法:
const { flow, intersection, pick } = require('lodash/fp');
data.filter(
flow(
pick(searchKeys),
entry => intersection(Object.values(entry)),
intersectWith => intersectWith(obligatory).length === obligatory.length &&
intersectWith(optional).length >= 1
)
);
它基本上归结为检查数据集(data
)的每个条目中的相关值(由searchKeys
标识)之间的交集,另一方面:
obligatory
数组的值:交集的长度必须为obligatory.length
。例如:它包含所有来自交叉点collection
optional
数组的值的项: obligatory
数组的长度必须为>= 1
。即:它包含至少1个来自optional
集合的项
这里有一个指向working repl的链接。
https://stackoverflow.com/questions/52467989
复制相似问题