Why does my array return a Undefined

Asked

Viewed 175 times

0

I have this code, but I want to access a certain attribute of a object who is within an array, but is returning Undefined

obj1 = {
    nome : 'name',
    array : [],
    funcao : function(element){this.array.push(element)},
    getArray : function(){return this.array},
    getNome : function(){this.array.forEach(element =>element.nome) }
}

obj2 = {
    nome: 'name2'
}

obj1.funcao(obj2)
console.log(obj1.getArray())
console.log(obj1.getNome())

  • 1

    Why is the return ?

1 answer

1

If you want to return a new array with the name property, try using the map method as follows:

obj1 = {
    nome : 'name',
    array : [],
    funcao : function(element){this.array.push(element)},
    getArray : function(){return this.array;},
    getNome : function(){return this.array.map(element =>element.nome) }
}

obj2 = {
    nome: 'name2'
}

obj1.funcao(obj2)
console.log(obj1.getArray())
console.log(obj1.getNome())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.