Leon Gaban Leon Gaban - 4 months ago 68
Javascript Question

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.

Answer

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:

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