如何在React中映射具有动态键的对象?

时间:2018-05-09 05:08:59

标签: javascript arrays reactjs

const arr = [
  {
    2671161009: {
      activityType: 'RUNNING',
      averageHeartRateInBeatsPerMinute: 134,
      comments: '',
      durationInSeconds: 3884,
      startTimeInSeconds: 1525368621,
      startTimeOffsetInSeconds: -14400,
      summaryId: '2671161009',
    },
    2671161249: {
      activityType: 'OTHER',
      averageHeartRateInBeatsPerMinute: 111,
      comments: '',
      durationInSeconds: 103,
      startTimeInSeconds: 1525372533,
      startTimeOffsetInSeconds: -14400,
      summaryId: '2671161249',
    },
  },
];

具有动态生成的索引键。我们如何在React中映射这个数组数据?你能不能给我一个建议。

2 个答案:

答案 0 :(得分:3)

您可以使用Object.entries访问对象的所有键值对:

<div>
  {arr.map(obj =>
    Object.entries(obj).map(([key, value]) => (
      <tr key={key}>
        <td>Key: {key}</td>
        <td>Activity Type: {value.activityType}</td>
        <td>DurationInSeconds: {value.durationInSeconds}</td>
      </tr>
    )))}
</div>

答案 1 :(得分:0)

嘿,单行代码怎么样

Object.entries(b[0]).map((item , index)=>
 <tr key={index}>
        <td>Activity Type: {item[1].activityType}</td>
        <td>DurationInSeconds: {item[1].durationInSeconds}</td>
  </tr>
)

Object.entries(b[0])中,您将获得数组中的条目,然后根据您的意愿循环该数组