i有一系列对象,我需要通过某个标准过滤。我很难弄清for循环中的if语句的逻辑。我已经连接了一个代码片段,您可以调整标准并查看我要解决的问题。非常感谢任何想法或建议,谢谢!
有了以下标准,我只能在我的founditems数组中找到1个项目:
const criteria = {
title: 'title',
character: 'Z',
type: ['second'],
};
这应该(并且确实(返回所有三个项目:
const criteria = {
title: 'title',
character: '',
type: [],
};
这应该返回前两个项目:
const criteria = {
title: 'title',
character: 'R',
type: [],
};
这应该返回所有三个项目:
const criteria = {
title: '',
character: '',
type: ['first','second'],
};
const data = [
{
label: {
title: 'A title',
},
character: 'R',
type: 'first',
},
{
label: {
title: 'Another title',
},
character: 'R',
type: 'second',
},
{
label: {
title: 'A more interesting title',
},
character: 'Z',
type: 'second',
},
];
const criteria = {
title: 'title',
character: 'Z',
type: ['second'],
};
const createRegEx = (value) => {
const regex = value
.split(' ')
.filter(Boolean)
.map((word) => `(?=^.*${word})`)
.join('');
return new RegExp(regex, 'i');
}
const foundItems = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
if (
item.label.title.match(createRegEx(criteria.title))
|| item.character === criteria.character
|| criteria.type.includes(item.type)
) {
foundItems[foundItems.length] = item;
}
}
console.log(foundItems);
这证明了我认为是您的意图。请让我知道是否需要纠正。我有一些自由来简化代码,但我不知道使用正则是必需的。
如果过滤器标准,该过滤器方法将过滤器应用于每个数据元素,以造成短语,匹配,返回true保留元素。
三元运算符为确定输入是否与比赛相关。如果空,则不会在该标准上过滤数据。
我相信您缺少的最后一点:
const data = [
{
label: {
title: 'A title',
},
character: 'R',
type: 'first',
},
{
label: {
title: 'Another title',
},
character: 'R',
type: 'second',
},
{
label: {
title: 'A more interesting title',
},
character: 'Z',
type: 'second',
},
];
const criteria = {
title: '',
character: 'R',
type: ['second'],
};
const foundItems = data.filter(item=>{
let t = (criteria.title.length)
? item.label.title.includes(criteria.title)
: true;
let c = (criteria.character.length)
? item.character === criteria.character
: true;
let p = (criteria.type.length)
? criteria.type.includes(item.type)
: true;
return t && c && p;
});
console.log(foundItems);