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

时间:2018-03-01 01:47:04

标签: javascript

我有一个对象数组,我需要按特定条件进行过滤。我在找出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);

1 个答案:

答案 0 :(得分:1)

这证明了我认为你的意图。如果需要纠正,请告诉我。我采取了一些自由来简化代码,但我不知道是否需要使用正则表达式。

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