I have a list of objects in where I need to find one specifically by an ID. So very simply like so:
{
{
"id": "1"
},{
"id": "2"
}
}
I have a function where I want to find the object by it's id, that does not work like so
function findOb (id) {
return _.find(myList, function(obj) { return obj.id === id } );
}
it is not returning the correct object (this is using lodash) uncertain what I am doing incorrect and could use some help. Thanks!
edit - I don't know if this helps but I am building and trying to search an object in this format - https://github.com/pqx/react-ui-tree/blob/gh-pages/example/tree.js . So there are just objects with module and leaf sometimes, and I want to be able to search and find by the 'module' key. Thanks for the feedback everyone!
1 Answer 1
Your code should have worked, but it can be simplified.
If you provide a property name for the predicate argument to _.find, it will search that property for the thisArg value.
function findOb(id) {
return _.find(myList, 'id', id);
}
The only problem I can see with your code is that you use === in your comparisons. If you pass 1 as the ID argument instead of "1", it won't match because === performs strict type checking.
[{id: 1}, {id: 2}].