1

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!

asked Oct 21, 2015 at 20:54
8
  • 5
    Your object doesn't have keys. Commented Oct 21, 2015 at 20:55
  • I am stuck like that right now, is there a way to achieve this without keys? Commented Oct 21, 2015 at 20:57
  • can you confirm this is a valid JSON object? it does not look like valid JSON Commented Oct 21, 2015 at 20:57
  • 3
    @ajmajmajma How about using an array of objects? [{id: 1}, {id: 2}]. Commented Oct 21, 2015 at 20:58
  • 1
    @ochi That's needed in JSON, but not in Javascript literals. Commented Oct 21, 2015 at 21:00

1 Answer 1

7

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.

answered Oct 21, 2015 at 20:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.