1
I am learning Javascript object orientation using Nodejs, and in a learning code I have created two classes: Person and Agenda, in which the Agenda has an array of the Person class, and in a search person by name function I have implemented I cannot get the result of the function.
Classes I created:
class Pessoa {
constructor(nome, telefone) {
this.nome = nome
this.telefone = telefone
}
}
class Agenda {
constructor(_options) {
this.pessoas = []
if (_options.length)
this.length = _options.length
else
this.length = 10
}
length() {
return this.length
}
adicionarPessoa(Pessoa) {
this.pessoas.push(Pessoa)
}
buscaPessoa(index) {
return this.pessoas[index]
}
buscaPessoaPorNome(nome) {
this.pessoas.forEach(async (pessoa, index)=>{
if (pessoa.nome === nome) {
return pessoa
}
})
}
listaPessoas() {
this.pessoas.forEach((pessoa, index)=>{
console.log(`ID: ${index}\n Nome: ${pessoa.nome}\n Telefone: ${pessoa.telefone}`)
})
}
}
Code where I ask and add 2 people to the agenda and try to access one by name:
var agenda = new Agenda({length: 10})
agenda.adicionarPessoa(new Pessoa('Bruno', '87 9 8000-5000'))
agenda.adicionarPessoa(new Pessoa('Luis', '87 9 1324-8962'))
var pessoa = agenda.buscaPessoaPorNome('Bruno')
console.log(pessoa.nome) //undefined <<---
I managed to solve using pessoas.find()
array.
buscaPessoaPorNome(nome) {
/* this.pessoas.forEach(async (pessoa, index)=>{
if (pessoa.nome === nome) {
return pessoa
}
}) */
return this.pessoas.find(e=>e.nome===nome)
}
Why don’t you use the method
Array.prototype.find()
for localization?return this.pessoas.find(e=>e===nome);
– Augusto Vasques
I don’t know if it would help because each person is an object, and I need to compare the property
nome
of him. I’ll change the question now.– Bruno Vinicius
You tested?
buscaPessoaPorNome(nome) {return this.pessoas.find(e=>e===nome);}
– Augusto Vasques
I just tested it the right way and got it! I forgot to put the
return
. Thank you!– Bruno Vinicius
I don’t know close the question yet. I’m trying to figure out.
– Bruno Vinicius
You can remove it or answer it like any user or leave it open for someone to answer it.
– Augusto Vasques
You answer, @Augustovasques!! If you have time for that, of course. : D
– Luiz Felipe
@Luizfelipe who knows later.
– Augusto Vasques