【问题标题】:indexOf on array of object instead of array [duplicate]indexOf 在对象数组而不是数组上[重复]
【发布时间】:2017-11-02 03:39:19
【问题描述】:

我知道在数组中查找值是否存在我可以使用 indexOf,但是如何使用对象数组来做到这一点?

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.indexOf('roadshows') ) // don't work

【问题讨论】:

  • 显然 indexOf 仅适用于原始类型值。你必须遍历数组
  • 没有内置函数可以做到这一点。您可以使用 underscore.js 或 lodash 之类的库来实现。否则你必须编写自己的循环。
  • x.map(o => o.id).indexOf('roadshows')
  • x.findIndex(o => o.id === 'roadshows')

标签: javascript ecmascript-6


【解决方案1】:

由于这被标记为,这里是一个ES6数组方法:Array#findIndex()

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( o => o.id === 'roadshows' ) )

如果您想要一种更可重复使用的方法,请考虑创建一个工厂isId(id)

function isId(id) {
  return (o) => o.id === id;
}

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( isId('roadshows') ) )

这被称为“工厂”,因为它是一个函数,它返回一个在其范围内具有传递参数的函数。

【讨论】:

    【解决方案2】:

    你有几个选择。

    首先,findIndex。你向它传递一个函数来测试一个元素是否是你正在寻找的,它返回第一个元素的索引,使该函数返回true

    x.findIndex((o) => o.id === 'roadshows');
    

    const x = [{
      "id": "roadshows",
      "name": "Roadshows"
    }, {
      "id": "sporting_events",
      "name": "Sporting Events"
    }];
    
    console.log(x.findIndex((o) => o.id === 'roadshows'));

    另一种选择是首先mapping 数组的相关属性和searching 在那个数组中。

    x.map((o) => o.id).indexOf('roadshows');
    

    const x = [{
      "id": "roadshows",
      "name": "Roadshows"
    }, {
      "id": "sporting_events",
      "name": "Sporting Events"
    }];
    
    console.log(x.map((o) => o.id).indexOf('roadshows'));

    【讨论】:

      【解决方案3】:

      如果你可以使用 es6 并且想返回有问题的对象,那么总是有Array.prototype.find()

      x.find( item => { return item.id === "roadshows" } )
      
      // returns {id: "roadshows", name: "Roadshows"}
      

      【讨论】:

        【解决方案4】:

        我会手动做这样的事情:

        for(let item of x) {
         if ( item.hasOwnProperty('id') && item['id'] == 'roadshows' ) {   
            //do your stuff here
         }
        }
        

        【讨论】:

          【解决方案5】:

          你必须循环遍历,因为你有对象的内部数组。

          for(var i = 0; i < x.length; i++) {
              if (x[i].id== 'roadshows') {
                  console.log(i);
                  break;
              }
          }
          

          或者,如果您只是检查具有该 id 的对象是否存在,过滤器很方便

          if (x.filter(function(e) x.id== 'roadshows').length > 0) {
            // Yay. Do Something
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-01-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-20
            • 1970-01-01
            • 2017-05-31
            相关资源
            最近更新 更多