我已经从firebase中拉下来,并被赋予了一个数组的有效载荷,其中有3个对象,它们本身包含对象。如何遍历数组内的对象内的对象
请看下面的截图:
这是当我CONSOLE.LOG我几个月阵列会发生什么。
我该如何迭代通过这个来注销我想从对象内部获得的任何信息?
例如我想要什么在月内和内部P1,P2。
我试图做
this.state.months.map()
然后登录month.month
但返回undefined。
有什么想法?
我已经从firebase中拉下来,并被赋予了一个数组的有效载荷,其中有3个对象,它们本身包含对象。如何遍历数组内的对象内的对象
请看下面的截图:
这是当我CONSOLE.LOG我几个月阵列会发生什么。
我该如何迭代通过这个来注销我想从对象内部获得的任何信息?
例如我想要什么在月内和内部P1,P2。
我试图做
this.state.months.map()
然后登录month.month
但返回undefined。
有什么想法?
如何在for
循环内对阵列使用for-in
循环?
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?
}
}
}
,这会在每次迭代中输出相同的值?即p1.score和p1.name会在每个循环中打印出来,而不是每次迭代时都会更改。如果这有什么意义 –
如何发布示例json? –
尝试以这种方式
jList = this.state.months
jList.map(jList=>(jList.month+ ", "+ jList.p1 + ", " + jList.p2))
输出 -将是一个数组
["some-Monthname, p1-someval, p2-someval", ... ]
只需根据您提供的截图中,你有对象的数组包含月份对象。您可以循环访问该数组,然后将它们映射到仅包含月份及其信息的数组中。这将使得处理这些月份更易于管理。
var months = this.state.months.forEach(function(item) {
return { month: item.month, p1: item.p1, p2: item.p2 };
});
然后你访问月份和它的数据就像这样。
console.log('Month is ', months[0].month, '. p1 object data is ', months[0].p1 '. and p2 object data is ', months[0].p2);
使用嵌套循环 – bigbounty
这些“-Kuog ...”是什么东西? – lilezek
我认为这些是由服务器生成的密钥。 @lilezek – bigbounty