0
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?

2
  • you can make it slightly shorter with for..in and .map(), but i dont see a way to do it with one loop Commented Sep 15, 2018 at 20:45
  • 2
    leagueInfo has only one property. If you know the property name already, the first loop is unnecessary. Commented Sep 15, 2018 at 20:50

3 Answers 3

2
leagueInfo.data.forEach(item => console.log(item.tier));
Sign up to request clarification or add additional context in comments.

Comments

1

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);
})

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.