indexOf method in an object array?

前端 未结 27 2441
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
27条回答
  •  孤独总比滥情好
    2020-11-22 02:43

    Using the ES6 findIndex method, without lodash or any other libraries, you can write:

    function deepIndexOf(arr, obj) {
      return arr.findIndex(function (cur) {
        return Object.keys(obj).every(function (key) {
          return obj[key] === cur[key];
        });
      });
    }
    

    This will compare the immediate properties of the object, but not recurse into the properties.

    If your implementation doesn't provide findIndex yet (most don't), you can add a light polyfill that supports this search:

    function deepIndexOf(arr, obj) {
      function findIndex = Array.prototype.findIndex || function (pred) {
        for (let i = 0; i < this.length; ++i) {
          if (pred.call(this, this[i], i)) {
            return i;
          }
        }
    
        return -1;
      }
    
      return findIndex.call(arr, function (cur) {
        return Object.keys(obj).every(function (key) {
          return obj[key] === cur[key];
        });
      });
    }
    

    (from my answer on this dupe)

提交回复
热议问题