Search code examples
javascriptarrayslodash

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


My objects:

[
    {
        description: 'object1', id: 1
    },
    {
        description: 'object2', id: 2
    }
    {
        description: 'object3', id: 3
    }
    {
        description: 'object4', id: 4
    }
]

In my function below I'm passing in the description to find the matching ID:

function pluckSavedView(action, view) {
    console.log('action: ', action);
    console.log('pluckSavedView: ', view);  // view = 'object1'

    var savedViews = retrieveSavedViews();
    console.log('savedViews: ', savedViews);

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

        console.log('delete_id: ', delete_id); // should be '1', but is undefined
    }
}

I'm trying to use lodash's find method: https://lodash.com/docs#find

However my variable delete_id is coming out undefined.


Update for people checking this question out, Ramda is a nice library to do the same thing lodash does, but in a more functional programming way :) http://ramdajs.com/0.21.0/docs/


Solution

  • 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]);