简体   繁体   中英

Filter against an array condition

Let's say I have an array of userIds

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

And then I have an array of objects

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

I want to filter my array of objects by matching ids to the userIds array

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

尝试这个

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

Array.prototype.includes isn't supported by Internet Explorer. If you want a cross browser solution you could use Array.prototype.filter and Array.prototype.indexOf methods:

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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