-1

I have pulled down from firebase and been given a payload of an array with 3 objects inside which themselves contain objects.

Consider the following screenshot:

enter image description here

This is what happens when i console.log my months array.

how do i iterate through this to log out any information i want from inside the object?

for example i want whats inside month and inside p1, p2.

i have tried to do

this.state.months.map() and then to log month.month but that returns undefined.

any ideas?

The Walrus
  • 1,148
  • 6
  • 28
  • 46

3 Answers3

0

how about using for-in loops inside the for loop against the array?

for (var i = 0, l = this.state.months.length; i < l; i++) {
  var obj = this.state.months[i];
  for (var key in obj) {
    //check if obj owns the property and not some prototype
    if (obj.hasOwnProperty(key)) {
      console.log(obj[key].p1); //what do we do with p1?
      console.log(obj[key].p2); //what do we do with p2?
    }
  }
}
xGeo
  • 2,149
  • 2
  • 18
  • 39
  • for some reason this prints out the same value in every iteration? i.e. p1.score and p1.name is printed out in every loop instead of it changing every time as it iterates. if that makes any sense – The Walrus Sep 24 '17 at 19:28
  • how about posting a sample json? – xGeo Sep 25 '17 at 06:08
0

Try in this way

jList = this.state.months
jList.map(jList=>(jList.month+ ", "+ jList.p1 + ", " + jList.p2))

OUTPUT- will be an array

["some-Monthname, p1-someval, p2-someval", ... ]  
krishnar
  • 2,537
  • 9
  • 23
0

Just based on the screenshot you provided, you have an array of objects that contain the month object. You can loop through that array and then map them into an array of just the months and their information. That will make dealing with the months more manageable.

var months = this.state.months.forEach( function( item ) {
    return { month: item.month, p1: item.p1, p2: item.p2 };
});

Then you access the month and its data like so.

console.log( 'Month is ', months[0].month, '. p1 object data is ', months[0].p1 '. and p2 object data is ', months[0].p2);
glennsl
  • 28,186
  • 12
  • 57
  • 75
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12