Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I loop over a group of JS objects and print a statement for each? [duplicate]

var teams = [
                {
                  city: 'Vancouver',
                  nickname: 'Canucks',
                  league: 'NHL'
                },
                {
                  city: 'San Jose',
                  nickname: 'Earthquakes',
                  league: 'MLS'
                },
                {
                  city: 'Sacramento',
                  nickname: 'Kings',
                  league: 'NBA'
                }
                        ]

document.write("The " + this.city + " " + this.nickname + " play in the " + this.league);

I want to loop through each and print the above statement for each. How would I best do this?

like image 785
Muirik Avatar asked Aug 16 '16 00:08

Muirik


1 Answers

var teams = [{
              city: 'Vancouver',
              nickname: 'Canucks',
              league: 'NHL'
            },
            {
              city: 'San Jose',
              nickname: 'Earthquakes',
              league: 'MLS'
            },
            {
              city: 'Sacramento',
              nickname: 'Kings',
              league: 'NBA'
            }];

for (var i = 0; i < teams.length; i++) {
   var team = teams[i];
   document.write("The " + team.city + " " + team.nickname + " play in the " + team.league + "<br/>");
}

The following will also work for you (keep in mind that arrow functions will not work in all browsers. So the previous example should probably be used)..

var teams = [{
              city: 'Vancouver',
              nickname: 'Canucks',
              league: 'NHL'
            },
            {
              city: 'San Jose',
              nickname: 'Earthquakes',
              league: 'MLS'
            },
            {
              city: 'Sacramento',
              nickname: 'Kings',
              league: 'NBA'
            }];

teams.forEach(team => {
    document.write("The " + team.city + " " + team.nickname + " play in the " + team.league + "<br/>");
});
like image 71
Meiji Avatar answered Sep 26 '22 01:09

Meiji