简体   繁体   English

如何遍历数组内对象内的对象

[英]How to iterate through objects inside objects inside an array

I have pulled down from firebase and been given a payload of an array with 3 objects inside which themselves contain objects.我已经从 firebase 拉下来,并获得了一个数组的有效负载,其中包含 3 个对象,其中包含对象。

Consider the following screenshot:考虑以下屏幕截图:

在此处输入图片说明

This is what happens when i console.log my months array.这就是当我 console.log 我的几个月数组时发生的情况。

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.例如,我想要月内和 p1、p2 内的内容。

i have tried to do我试过做

this.state.months.map() and then to log month.month but that returns undefined. this.state.months.map()然后记录month.month . month.month但返回未定义。

any ideas?有任何想法吗?

how about using for-in loops inside the for loop against the array?有关如何使用for-in循环内for对数组循环?

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 OUTPUT-将是一个数组

["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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM