0

Hello i just want to know how to iterate this array

```

[ { "0": { "player_id": "138", "player_name": "Pring", "profile_image": "", "score_card": [ "0" ], "total_score": 22 }, "1": { "player_id": "4", "player_name": "Poring 12", "profile_image": "", "score_card": [ "0", ], "total_score": 0 }, "date": "2017-09-21", "start_time": "17:40:00", "end_time": "18:00:00" } ] 

```

or maybe group by players with lodash? im requesting to an api, but it seems that is not a cool one, or maybe im not good enough to perform this kind of arrays, (is my head hurt)

8
  • that is an array with one element - so, not much to iterate in reality Commented Oct 4, 2017 at 0:25
  • You loop through for objects properties using Object.keys or Object.getOwnPropertyNames Commented Oct 4, 2017 at 0:25
  • i can't write all the code, because SO doesn't leave me, but the real code has more than one objet in array, so it's needed to iterate @JaromandaX Commented Oct 4, 2017 at 0:26
  • oh, ok, so you want to iterate the array ... use .map or .forEach or .reduce - it's hard to tell which without you at least showing what output you require Commented Oct 4, 2017 at 0:27
  • this is all the code codepen.io/dcergo/pen/aLVOyv Commented Oct 4, 2017 at 0:29

1 Answer 1

2

If you want to loop through objects in an array, you can do this

for(var i=0; i<your_array.length; i++){ var object = your_array[i] //your code here } 

If you want to loop through properties in an object, you can do this

for(var propName in object){ var prop = object[propName] //Your code here } 

If you only want to loop through properties with numeric format name, you can do this

for(var propName in object){ if(!isNaN(propName)){ var prop = object[propName] //Your code here } } 

Altogether,

for(var i=0; i<your_array.length; i++){ var object = your_array[i]; console.log("From " + object.start_time + " to " + object.end_time); for(var propName in object){ if(!isNaN(propName)){ var playerIndex = propName; var player = object[propName] console.log("Index = " + playerIndex + ", ID = " + player.player_id + ", Name = " + player.player_name); } } } 

Output

From 17:40:00 to 18:00:00 Index = 0, ID = 138, Name = Jay Patoliya From 17:00:00 to 18:00:00 Index = 0, ID = 138, Name = Jay Patoliya From 17:40:00 to 18:00:00 Index = 0, ID = 138, Name = Jay Patoliya Index = 1, ID = 4, Name = Jay Patoliya Index = 2, ID = 49, Name = John DiFulvio 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! this is very helpful!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.