I have the following array of objects from which I am trying to get the value "kitty2" from the property "children" of the second object.
let animales = [
{tipo: "perro", edad:12, nombre:"rocky"},
{tipo: "gato", edad:19, nombre:"boby", hijos:["gatito1","gatito2","gatito3"]},
{tipo: "hamster", edad:2, nombre:"balboa"}
]
I have tried with map but it returns all the kittens, also with 2 undefined values that I don't know where they came from:
[ undefined, [ 'gato1', 'gato2', 'gato3' ], undefined ]
This is the code I am testing
let animales = [
{tipo: "perro", edad:12, nombre:"rocky"},
{tipo: "gato", edad:19, nombre:"boby", hijos:["gatito1","gatito2","gatito3"]},
{tipo: "hamster", edad:2, nombre:"balboa"}]
const recorrer = animales.map(function(animal){
return animal.hijos;
})
console.log(recorrer);
What is happening to you is that the .map tries to find the property
hijos
in all the elements and since you only have it defined in the oftipo: "gato"
, it returns youundefined
in thetipo: "perro"
and thetipo: "hamster"
.To avoid that, first use .filter so that only the elements of the
tipo: "gato"
:Then if you want to get only the value
"gatito2"
you can put in the map so that it only shows the second value of the array:In this way it would be something like this: