Underscore js find item by ID

前端 未结 3 535
滥情空心
滥情空心 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条回答
  • 2020-12-13 18:22

    Update

    It's 2016 and we might not acutally need underscore to achieve that. Using Array.prototype.find(). It returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.

      // Underscore
      var users = [
        { 'user': 'barney',  'age': 36, 'active': true },
        { 'user': 'fred',    'age': 40, 'active': false },
        { 'user': 'pebbles', 'age': 1,  'active': true }
      ]
    
      _.find(users, function (o) { return o.age < 40; })
      // output: object for 'barney'
    
      // Native
      var users = [
        { 'user': 'barney',  'age': 36, 'active': true },
        { 'user': 'fred',    'age': 40, 'active': false },
        { 'user': 'pebbles', 'age': 1,  'active': true }
      ]
    
      users.find(function (o) { return o.age < 40; })
      // output: object for 'barney'
    

    Browser support

    --------------------------------------------
    | Chrome | Firefox | Safari |  IE  | Opera |
    |--------|---------|--------|------|-------|
    |   45   |    25   |  7.1   | Edge |  32   |
    --------------------------------------------
    

    More information an polyfill on MDN


    Update: I found that _.where always returns an array. _.findWhere returns the first object it finds so it will be better to use if you expect a single object in return.


    You can use _.where It's much easier.

    If it's something like this :

    var goal  = [
    
        {
            "category" : "education",
            "title" : "Charlie University",
            "description" : "Lorem ipsum dolor sit amet",
            "date" : "01/03/2020",
            "value" : 50000,
            "achievability" : 3,
            "experimental_achievability": 3,
            "suggested": false,
            "accounts": [],
            "articles": [],
            "related_goals": [],
            "id":"1"
        },
        {
            "category" : "education",
            "title" : "Charlie University",
            "description" : "Lorem ipsum dolor sit amet",
            "date" : "01/03/2020",
            "value" : 50000,
            "achievability" : 3,
            "experimental_achievability": 3,
            "suggested": false,
            "accounts": [],
            "articles": [],
            "related_goals": [],
            "id":"2"
        },
        {
            "category" : "education",
            "title" : "Charlie University",
            "description" : "Lorem ipsum dolor sit amet",
            "date" : "01/03/2020",
            "value" : 50000,
            "achievability" : 3,
            "experimental_achievability": 3,
            "suggested": false,
            "accounts": [],
            "articles": [],
            "related_goals": [],
            "id":"3"
        },
        {
            "category" : "education",
            "title" : "Charlie University",
            "description" : "Lorem ipsum dolor sit amet",
            "date" : "01/03/2020",
            "value" : 50000,
            "achievability" : 3,
            "experimental_achievability": 3,
            "suggested": false,
            "accounts": [],
            "articles": [],
            "related_goals": [],
            "id":"4"
        }
    ]
    

    You can use something like :

    var filteredGoal = _.where(goal, {id: "1"});
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-13 18:34

    Have simplified your data model, but something like this?

    var goals = [{id:1, name:'Goal1'},
                 {id:2, name:'Goal2'},
                 {id:3, name:'Goal3'}];
    
    function getGoal(id) {
        return _.find(goals, function(goal) {
            return goal.id === id;
        });
    }
    
    alert(getGoal(2).name);
    

    You can see this in action in this jsFiddle.

    0 讨论(0)
提交回复
热议问题