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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.