Underscore js find item by ID

前端 未结 3 536
滥情空心
滥情空心 2020-12-13 17:34

I\'m new to Underscore js and bit confused on how to use it. I have a collection of \'goals\' and I want to find one of it by ID.

here\'s the data:

{         


        
3条回答
  •  -上瘾入骨i
    2020-12-13 18:33

    You are using Array of objects. So,you can use: _.findWhere(Looks through the list and returns the first value that matches all of the key-value pairs ) to get the all the properties based on id or other key attribute.

    var some= [
                 {Employee:'ved',id:20}, 
                 {Employee:"ved",age:25},
                 {Employee:"p",age:2}
              ];
    
    var a = _.findWhere(some,{id:20});
    console.log('searchResult',a);
    

    To get the index, you can use something like this:

    var b = _.indexOf(some,a);
    console.log('index',b);
    

    If you need all list of uses,
    TRY: _.where(It looks through each occurrence in the array, returning an array of all the values that contain the key-value pairs listed in properties.)

    var some= [ 
                {Employee:"ved",id:20}, 
                {Employee:"ved prakash",id:20},
                {Employee:"anyone",id:2}
              ];
    var a = _.where(some,{id:25});
        console.log('searchResult',a);
    

    _.find: It is used to check the value only, not Key-value both.


    Visit Docs:_.find

提交回复
热议问题