Best way to loop through array object

3788 views javascript

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?

answered question

you can make it slightly shorter with and .map(), but i dont see a way to do it with one loop

leagueInfo has only one property. If you know the property name already, the first loop is unnecessary.

3 Answers

0 => console.log(item.tier));

posted this

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); {
       console.log('5on5 ranked', values.tier );

And here's a link to W3Schools where you can find all possible actions with arrays.

posted this

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"}]} => {

posted this

Have an answer?


Please login first before posting an answer.