在循环内按数组属性过滤集合

时间:2018-11-17 23:52:17

标签: javascript arrays

我正在尝试过滤作为数组的属性上的集合。例如,我有一个收藏集:

const collection = [
  {
    name: 'one',
    type: ['BRANCH']
  },
  {
    name: 'Two',
    type: ['OTHER']
  },
  {
    name: 'Three',
    type: ['OTHER']
  },
]

我有一个过滤器,它也是一个数组:

const filter = ['BRANCH']

现在,我尝试仅返回集合中与过滤器数组匹配的项目。我有以下代码要重构:

const filtered = [];

collection.forEach((item) => {
  item.type.forEach((type) => {
    if (filters.indexOf(type) !== -1) {
      filtered.push(item);
    }
  })
})

console.log(filtered);

是否有更好的方法在循环内比较这些数组(item.typefilter)以仅返回集合中匹配的项目?

Demo

2 个答案:

答案 0 :(得分:1)

您当前的逻辑可能无法实现您想要的结果-如果type中有多个项目与filter中的某个项目匹配,则数组项目将被推送两次 (或更多)。

例如:

const collection = [
  {
    name: 'one',
    type: ['BRANCH']
  },
  {
    name: 'Two',
    type: ['OTHER']
  },
  {
    name: 'Three',
    type: ['OTHER']
  },
  {
    name: 'one',
    type: ['BRANCH', 'FOO']
  },
];
const filters = ['BRANCH', 'FOO']
const filtered = [];
collection.forEach((item) => {
  item.type.forEach((type) => {
    if (filters.indexOf(type) !== -1) {
      filtered.push(item);
    }
  })
})
console.log(filtered);

相反,您可以使用Array.prototype.filter并检查.some数组中是否包含type filter

const collection = [
  {
    name: 'one',
    type: ['BRANCH']
  },
  {
    name: 'Two',
    type: ['OTHER']
  },
  {
    name: 'Three',
    type: ['OTHER']
  },
]
const filter = ['BRANCH'];

console.log(
  collection.filter(({ type }) => (
    type.some(item => filter.includes(item))
  ))
);

假设type中包含filter中的 some 个,则您希望结果中包含项。如果要检查filter每个项是否在type数组中,请在Array.prototype.every数组上使用filter

const collection = [
  {
    name: 'one',
    type: ['BRANCH']
  },
  {
    name: 'Two',
    type: ['OTHER']
  },
  {
    name: 'Three',
    type: ['OTHER']
  },
]
const filter = ['BRANCH'];

console.log(
  collection.filter(({ type }) => (
    filter.every(item => type.includes(item))
  ))
);

答案 1 :(得分:1)

使用filter过滤对象,使用everyincludes检查数组是否相等:

const filtered = collection.filter(obj =>
    obj.type.every(item => filter.includes(item))
);

读取内容:从数组collection过滤对象,其中每个对象的type数组是数组filter的子集。

示例:

const collection = [ { name: 'one', type: ['BRANCH'] }, { name: 'Two', type: ['OTHER'] }, { name: 'Three', type: ['OTHER'] } ];

const filter = ['BRANCH'];

const filtered = collection.filter(obj =>
    obj.type.every(item => filter.includes(item))
);

console.log(filtered);

相关问题