React中数组中对象的.map

时间:2016-05-21 22:42:46

标签: javascript reactjs jsx

我试图在React中循环包含包含其中对象的数组的对象,并且我在.map函数上收到错误。以下是.map函数,后跟this.state

中对象的外观

.MAP:

//trying to access January from the object which is 0 starting month
let daysOfWeeks = this.state[0].map(function (day, i){
    ...
}

以下是该对象的示例:

//0 is January, 1 is February, and so on... inside has objects that have the day number and day of week
let result = {
    0:[ 
        {dayNumber:1,dayOfWeek:"fri"},
        {dayNumber:2,dayOfWeek:"sat"},
        {dayNumber:3,dayOfWeek:"sun"},
        ...
      ],
    1:[
        {dayNumber:1,dayOfWeek:"mon"},
        {dayNumber:2,dayOfWeek:"tue"},
        {dayNumber:3,dayOfWeek:"wed"},
        ...
      ],
    2:[
        {dayNumber:1,dayOfWeek:"tue"},
        {dayNumber:2,dayOfWeek:"wed"},
        {dayNumber:3,dayOfWeek:"thur"},
        ...
      ],

    ...
};

//result is in a function that is returned and set state is calling the function and setting state to the object itself -- here is setState:

this.setState(getDaysArray(y,m));

//getDaysArray(y,m) returns that object above

.map中我想要的是白天成为我循环的对象。 day.dayNumberday.dayOfWeek

... .map(function(day, i){
    return(
        <div>
            <div>{day.dayNumber}</div>
            <div>{day.dayOfWeek}</div>
        </div>
    )
}

但我认为问题.map上的错误this.state[0]是什么问题。任何人都知道我如何访问和循环父对象内的数组中的对象?

1 个答案:

答案 0 :(得分:2)

尝试this.state.result['0'].map(...)

当你有一个像这样的对象时,用一个数字作为键,即使键是一个&#39;数字;你以字符串形式访问它。默认情况下,对象键是字符串。

let result = {
    0:[ 
        {dayNumber:1,dayOfWeek:"fri"},
        {dayNumber:2,dayOfWeek:"sat"},
        {dayNumber:3,dayOfWeek:"sun"},
        ...
      ]
}