I have an array called persons, that contains objects and arrays within. I'm trying to get all the first names in the siblings array to display. I have a for loop that is displaying John and Maria, but when i call the siblings, the only names that display are Jenny and Jose. I tried different things, Is there a way to display all the firstnames within the siblings array?
var persons = [{
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue",
weight: 180,
siblings: [
{firstName:"Jenny",
age:43,
eyecolor:"brown",},
{firstName:"Jim",
age:35,
eyecolor:"green",},
{firstName:"Joe",
age:29,
eyecolor:"black",},
] },
{firstName:"Maria",
lastName:"Lopez",
age:19,
eyeColor:"brown",
weight: 120,
siblings: [
{firstName:"George",
age:25,
eyecolor:"brown",},
{firstName:"Jose",
age:20,
eyecolor:"green",},
]},
];
for(i=0; i<persons.length; i++){
console.log(persons[i].firstName);
console.log(persons[i].siblings[i].firstName);
}
You should use the Array.forEach() method to easily loop through the array items. Then just console.log the firstname.
var persons = [{
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue",
weight: 180,
siblings: [{
firstName: "Jenny",
age: 43,
eyecolor: "brown",
},
{
firstName: "Jim",
age: 35,
eyecolor: "green",
},
{
firstName: "Joe",
age: 29,
eyecolor: "black",
},
]
},
{
firstName: "Maria",
lastName: "Lopez",
age: 19,
eyeColor: "brown",
weight: 120,
siblings: [{
firstName: "George",
age: 25,
eyecolor: "brown",
},
{
firstName: "Jose",
age: 20,
eyecolor: "green",
},
]
},
];
persons.forEach(person => console.log(person.firstName))