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 - .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!
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./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!
Share Improve this question edited Oct 21, 2015 at 21:02 ajmajmajma asked Oct 21, 2015 at 20:54 ajmajmajmaajmajmajma 14.2k25 gold badges83 silver badges138 bronze badges 8- 5 Your object doesn't have keys. – Oriol Commented Oct 21, 2015 at 20:55
- I am stuck like that right now, is there a way to achieve this without keys? – ajmajmajma Commented Oct 21, 2015 at 20:57
- can you confirm this is a valid JSON object? it does not look like valid JSON – blurfus Commented Oct 21, 2015 at 20:57
-
3
@ajmajmajma How about using an array of objects?
[{id: 1}, {id: 2}]
. – Sebastian Simon Commented Oct 21, 2015 at 20:58 - 1 @ochi That's needed in JSON, but not in Javascript literals. – Barmar Commented Oct 21, 2015 at 21:00
1 Answer
Reset to default 7Your 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 parisons. If you pass 1
as the ID argument instead of "1"
, it won't match because ===
performs strict type checking.