根据数组条件过滤

时间:2018-12-20 19:43:51

标签: javascript arrays object filter

假设我有一个userIds数组

const userIds = ['1234', '3212', '1122']

然后我有一个对象数组

const arrayOfObjects = [
  {
    _source: {itemId: ['1234'] }
  },
  {
    _source: {itemId: ['3212'] }
  },
  {
    _source: {itemId: ['1111'] }
  }
]

我想通过将id与userIds数组匹配来过滤对象数组

arrayOfObjects.filter(item => item._source.itemId === "what goes here?")

2 个答案:

答案 0 :(得分:3)

尝试一下

arrayOfObjects.filter(item => userIds.includes(item._source.itemId[0]))

答案 1 :(得分:1)

Internet Explorer不支持

Array.prototype.includes。如果需要跨浏览器解决方案,则可以使用Array.prototype.filterArray.prototype.indexOf方法:

const userIds = ['1234', '3212', '1122'];
const arrayOfObjects = [{
    _source: {
      itemId: ['1234']
    }
  },
  {
    _source: {
      itemId: ['3212']
    }
  },
  {
    _source: {
      itemId: ['1111']
    }
  }
];

const filtered = arrayOfObjects.filter(o => userIds.indexOf(o['_source'].itemId[0]) > -1);

console.log(filtered)