Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Pass Parameter in javascript find function?

Tags:

javascript

Hie,

I have a json object which have a id field:

document = {
             id: 'some value',
             ...
           }

And a list to store this documents.

var list = [{document}, {document} ...]

Now I am trying to call javascript find() function on the list to return the document with a specific id as

list.find( document, id) => {
   if (document.id == id)
   return id
}

But its not working. I checked and found that the id parameter value is not what I am passing but the index value of the document in the list. I tried changing the name hoping it was a error with keyword but the sae result.

So, How do I pass a custom parameter to the find function?

like image 389
sam23 Avatar asked Jun 06 '17 13:06

sam23


1 Answers

It's a call back method that allows you to reference to variables outside of the scope of the callback.

Example:

var id = 10;
var foundDoc = list.find((document) => document.id == id);

// alternative syntax
var foundDoc = list.find((document) => {
  return document.id == id;
});

In your example find takes a predicate that should return true/false if there is a match. On the first occurance of true (a match) that item is returned to the caller.

like image 176
Igor Avatar answered Nov 02 '22 22:11

Igor