Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display array of objects not working in browser

I am wanting to create an array of objects and display a specific list of properties when certain conditions are met.

The following code does what I want when I print it to the console or use document.write.

var people = [{ 
    firstName: 'John',
    lastName: 'Doe',
    age: 23,
    },{ 
    firstName: 'Jane',
    lastName: 'Doe',
    age: 53,
    }]

    for(i = 0; i < people.length; i++){
        if(people[i].age < 65){
            document.write(people[i].firstName + ' ' + 
            people[i].lastName + ' has printed to document. <br>');             
        }
    }

But when I go to run the code in the browser, using document.getElementById, only the last item is displaying.

for(i = 0; i < people.length; i++){
    if(people[i].age < 65){
        result = 'Only ' + people[i].firstName + ' ' + 
            people[i].lastName + ' is printed to document. Why?';               
    }
}
document.getElementById('names').innerHTML = result;

Could someone explain to me why all items appear using document.write? While only the last item appears when using document.getElementById?

like image 280
Don199 Avatar asked May 05 '26 00:05

Don199


1 Answers

The issue is in this line:

result = 'Only ' + people[i].firstName + ' ' + 
        people[i].lastName + ' is printed to document. Why?';

Because you're assigning the message string to result variable. Since you are in a loop, the result variable will just hold the last value.

You have to concat the message to result variable.

for(i = 0; i < people.length; i++){
    if(people[i].age < 65){
        result += 'Only ' + people[i].firstName + ' ' + 
            people[i].lastName + ' is printed to document. Why?';               
    }
}

Also, you can use string templates for formatting the message.

result += `Only ${people[i].firstName} ${people[i].lastName} is printed to document. Why?`;
like image 166
Mihai Alexandru-Ionut Avatar answered May 06 '26 20:05

Mihai Alexandru-Ionut