Medy
Medy

Reputation: 55

Best way to loop through array object

leagueInfo = {"data":[{"tier":"Gold"},{"tier":"Bronze"}]}

So far I have been doing 2 for loops like this:

for (const key of Object.keys(leagueInfo)) {
  console.log('5on5 ranked', leagueInfo[key]);
  // Array (2)  is output

  for (const values of leagueInfo[key]) {
    console.log('5on5 ranked', values.tier );
    // Output is :
    // Gold
    // Bronze
  }
}

Do I really need 2 loops or is there a shorter way of doing this?

Upvotes: 0

Views: 65

Answers (3)

Alejandro Vales
Alejandro Vales

Reputation: 2937

There are several ways.

You could use methods from the lodash or underscore libraries, that are replicas of how the .foreach or for loops work.

If the data that you have is always the same and similar to the one posted you can do the following to iterate through the data items that you have in the array. Keep in mind that the first iteration you are doing is useless, since you could access the property directly.

var leagueInfo = {"data":[{"tier":"Gold"},{"tier":"Bronze"}]}

leagueInfo.data.forEach((item) => {
  console.log(item);
  console.log(item.tier);
})

Upvotes: 1

Nerijus Pamedytis
Nerijus Pamedytis

Reputation: 134

There is dozens of ways to iterate objects or arrays. And usually with functions specifically adapted for certain goals in mind. if you want to only console.log iteration result you can use .map()

var leagueInfo = {"data":[{"tier":"Gold"},{"tier":"Bronze"}]};

Object.values(leagueInfo).map(function(dataArray) {
     console.log('5on5 ranked', dataArray);
    dataArray.map(function(values) {
       console.log('5on5 ranked', values.tier );
    })
})

And here's a link to W3Schools where you can find all possible actions with arrays. https://www.w3schools.com/jsref/jsref_obj_array.asp

Upvotes: 0

Vladimir Makushev
Vladimir Makushev

Reputation: 114

leagueInfo.data.forEach(item => console.log(item.tier));

Upvotes: 2

Related Questions