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:
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?
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?
}
}
}
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", ... ]
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.