繁体   English   中英

针对另一个对象过滤对象数组

[英]Filtering an array of objects against another object

我有一些对象,需要按特定条件过滤。 我在弄清楚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); 

这表明我相信是您的意图。 请让我知道是否需要更正。 我有些自由地简化了代码,但是我不知道是否需要使用正则表达式。

filter方法对每个数据元素应用一个过滤器,如果该过滤器的标准是匹配一个短语,则匹配,返回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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM