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

前端 未结 7 798
滥情空心
滥情空心 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 08:18

    I'd strongly suggest taking a look at lodash. It contains quite a bit of nifty little functions that unfortunately underscore is lacking.

    For example, this is what you would do with lodash:

    var array = [{'id': 1, 'name': 'xxx'},
               {'id': 2, 'name': 'yyy'},
               {'id': 3, 'name': 'zzz'}];
    
    var searchValue = {'id': 1, 'name': 'xxx'};
    
    
    var index = _.findIndex(array, searchValue); 
    console.log(index === 0); //-> true
    

    http://lodash.com/docs#findIndex

    Also, if you're bound to using Underscore - you can grab lodash's underscore build at https://raw.github.com/lodash/lodash/2.4.1/dist/lodash.underscore.js


    ES2015

    With ES2015 now in wide use (through transpilers like Babel), you could forego lodash and underscore for the task at hand and use native methods:

    var arr = [{ id: 1 }, { id: 2}];
    
    arr.findIndex(i => i.id === 1); // 0
    

提交回复
热议问题