【问题标题】:Filter against an array condition根据数组条件过滤
【发布时间】:2018-12-20 19:43:50
【问题描述】:

假设我有一个 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?")

【问题讨论】:

    标签: javascript arrays object filter


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      Array.prototype.includes 不受 Internet Explorer 支持。如果您想要一个跨浏览器解决方案,您可以使用 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)

      【讨论】:

        猜你喜欢
        • 2018-10-04
        • 1970-01-01
        • 2022-11-23
        • 2018-10-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        • 2019-08-03
        相关资源
        最近更新 更多