I want to loop through an array of objects in a function.
The problem, when I use return, it only returns the first result, in this case Olaf Kranz
, but I want to return all first and last names like:
Olaf Kranz
Mark Alien
Cindy Sunsi
Anna Pitter
Piet Schmitz
var allInfo = [
{name: "Olaf", lastname: "Kranz", age:33},
{name: "Mark", lastname: "Alien", age:21},
{name: "Cindy", lastname: "Sunsi", age:65},
{name: "Anna", lastname: "Pitter", age:20},
{name: "Piet", lastname: "Schmitz", age:29}
];
function getAllFirstAndLastnames() {
for (i = 0; i < allInfo.length; i++){
return allInfo[i].name + " " + allInfo[i].lastname + "\n";
}
};
document.write(getAllFirstAndLastnames());
When you return
, it immediately terminates the function - you're only going through one iteration. Add to an HTML string instead. Also make sure to use <br>
for HTML rather than \n
:
var allInfo = [{ name: "Olaf", lastname: "Kranz", age: 33 }, { name: "Mark", lastname: "Alien", age: 21 }, { name: "Cindy", lastname: "Sunsi", age: 65 }, { name: "Anna", lastname: "Pitter", age: 20 }, { name: "Piet", lastname: "Schmitz", age: 29 }];
function getAllFirstAndLastnames() {
let htmlString = '';
for (let i = 0; i < allInfo.length; i++) {
htmlString += allInfo[i].name + " " + allInfo[i].lastname + "<br>";
}
return htmlString;
}
document.write(getAllFirstAndLastnames());
But this would be cleaner with .map
followed by .join
:
var allInfo = [{ name: "Olaf", lastname: "Kranz", age: 33 }, { name: "Mark", lastname: "Alien", age: 21 }, { name: "Cindy", lastname: "Sunsi", age: 65 }, { name: "Anna", lastname: "Pitter", age: 20 }, { name: "Piet", lastname: "Schmitz", age: 29 }];
function getAllFirstAndLastnames() {
return allInfo
.map(({ name, lastname }) => name + ' ' + lastname)
.join('<br>');
}
document.write(getAllFirstAndLastnames());