javascript - React 数组中对象的 .map

标签 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 成为我循环遍历的对象。 day.dayNumberday.dayOfWeek

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

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

最佳答案

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

当你有一个像这样的对象时,以数字作为键,即使键是“数字”;您将其作为字符串访问。默认情况下,对象键是字符串。

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

关于javascript - React 数组中对象的 .map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368717/

相关文章:

javascript - 倒计时( cookies )

javascript - 自定义复选框在 ie7 和 ie8 中重复

javascript - Gulp Bundle + Browserify 处理多个文件

reactjs - Rollup + React 不编译 JSX

javascript - Node.js:意外省略 var 声明通过全局对象、错误或功能公开所有变量?

javascript - 类型错误 : undefined is not an object (evaluating 'this.__reactAutoBindMap' )

c# - 通过 React 客户端应用程序连接到 Ocelot Api 网关中的 SignalR 集线器时,出现未处理的拒绝(错误)(HttpError)

reactjs - React div 容器 onClick 与复选框 onChange 冲突

javascript - 在 Apollo Client 中取消订阅

html - VScode : how-to change the color of HTML open and closing tag