How to use lodash to find and return an object from Array?

前端 未结 10 1080
终归单人心
终归单人心 2020-11-29 18:58

My objects:

[
    {
        description: \'object1\', id: 1
    },
    {
        description: \'object2\', id: 2
    }
    {
        description: \'object3\         


        
相关标签:
10条回答
  • 2020-11-29 19:55

    lodash and ES5

    var song = _.find(songs, {id:id});
    

    lodash and ES6

    let song = _.find(songs, {id});
    

    docs at https://lodash.com/docs#find

    0 讨论(0)
  • 2020-11-29 19:57
    var delete_id = _(savedViews).where({ description : view }).get('0.id')
    
    0 讨论(0)
  • 2020-11-29 19:59

    The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}.

    var delete_id = _.result(_.find(savedViews, function(obj) {
        return obj.description === view;
    }), 'id');
    

    Yet another alternative from the docs you linked to (lodash v3):

    _.find(savedViews, 'description', view);
    

    Lodash v4:

    _.find(savedViews, ['description', view]);
    
    0 讨论(0)
  • 2020-11-29 20:01

    You don't need Lodash or Ramda or any other extra dependency.

    Just use the ES6 find() function in a functional way:

    savedViews.find(el => el.description === view)
    

    Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

    • bloat your bundled code size,
    • you will have to keep them up to date,
    • and they can introduce bugs or security risks
    0 讨论(0)
提交回复
热议问题