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;
}
Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With