Enrikisimo Lopez Ramos
Enrikisimo Lopez Ramos

Reputation: 393

Array.prototype.find to search an Object in an Array

I am using Array.prototype.find to search an Object Person in an Array. I would like use the id to find this Object. I've been reading about the method find (ES6) but I don't know why my code is wrong.

This is my code:

AddresBook.prototype.getPerson = function (id) {

    return this.lisPerson.find(buscarPersona, id);

};

function buscarPersona(element, index, array) {
    if (element.id === this.id) {
        return element;
    } else
        return false;
}

Upvotes: 6

Views: 1483

Answers (2)

Bergi
Bergi

Reputation: 664548

You're passing the id directly as the thisArg parameter to .find(), but inside buscarPersona you expect this to be an object with a .id property. So either

  • pass an object:

    lisPerson.find(buscarPersona, {id});
    function buscarPersona(element, index, array) {
        return element.id === this.id;
    }
    
  • use this directly:

    lisPerson.find(buscarPersona, id);
    function buscarPersona(element, index, array) {
        // works in strict mode only, make sure to use it
        return element.id === this;
    }
    
  • just pass a closure

    lisPerson.find(element => element.id === id);
    

Upvotes: 4

caballerog
caballerog

Reputation: 2739

A dirty solution could be added the last_id in the AddressBook's Prototype.

So your code would be the following

AddressBook.prototype.getPerson = function(id){
    this.last_id = id;
    return this.lisPerson.find(buscarPersona,this);
}
function buscarPersona(element){
    if(element.id === this.last_id){
        return element;
    }else{
        return false;   
    }
}

Upvotes: 1

Related Questions