How can I find the index of an object inside a Array using underscore.js?

前端 未结 7 971
滥情空心
滥情空心 2021-02-14 07:45

I want to get the index of the given value inside a Array using underscore.js.

Here is my case

var array = [{\'id\': 1, \'name\': \'xxx\'},
                      


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 08:21

    Use this instead:

    var array = [{'id': 1, 'name': 'xxx'},
                 {'id': 2, 'name': 'yyy'},
                 {'id': 3, 'name': 'zzz'}];
    
    var searchValue = {'id': 1, 'name': 'xxx'},
        index = -1;
    
    _.each(array, function(data, idx) { 
       if (_.isEqual(data, searchValue)) {
          index = idx;
          return;
       }
    });
    
    console.log(index); //0
    

    In your snippet data === searchValue compares the objects' references, you don't want to do this. On the other hand, if you use data == searchValue you are going to compare objects' string representations i.e. [Object object] if you don't have redefined toString methods.

    So the correct way to compare the objects is to use _.isEqual.

提交回复
热议问题