首页 > 解决方案 > React:如何将 JSON 对象转换为数组并渲染它?

问题描述

我有一个包含英雄联盟冠军信息的大型本地 JSON 文件。我想输出随机冠军数据(姓名、头衔等)。为此,我将其转换为 Object,然后再转换为 Array,以便可以将其与 map() 一起使用。问题是,当我将它从 Object 转换为 Array 时,我会丢失我认为不正确的属性名称。

JSON 文件中所有属性名称的对象示例

champObject:
id: "jarvaniv"
key: "59"
name: "Jarvan IV"
sprite: {url: "http://ddragon.leagueoflegends.com/cdn/8.11.1/img/sprite/champion1.png", x: 96, y: 48}
stats: {hp: 571.2, hpperlevel: 90, mp: 302.2, mpperlevel: 40, movespeed: 340, …}
tags: (2) ["Tank", "Fighter"]
title: "the Exemplar of Demacia"
__proto__: Object

转换为数组示例。请注意没有属性名称

champData: Array(9)
0: "jarvaniv"
1: "59"
2: "Jarvan IV"
3: "the Exemplar of Demacia"
4: (2) ["Tank", "Fighter"]
5: {hp: 571.2, hpperlevel: 90, mp: 302.2, mpperlevel: 40, movespeed: 340, …}
6: "http://ddragon.leagueoflegends.com/cdn/8.11.1/img/champion/JarvanIV.png"
7: {url: "http://ddragon.leagueoflegends.com/cdn/8.11.1/img/sprite/champion1.png", x: 96, y: 48}
8: "Prince Jarvan, scion of the Lightshield dynasty, is heir apparent to the throne of Demacia. Raised to be a paragon of his nation's greatest virtues, he is forced to balance the heavy expectations placed upon him with his own desire to fight on the front..."
length: 9
__proto__: Array(0)

这就是我在 MainPage.js 中使用它的方式。如您所见,我希望在我的 JSON 文件中具有准确的属性名称,以便我可以输出一些我选择的特定数据。

import ChampionsData from '../data/champions.json'

class MainPage extends React.Component {

render(){
const keys = Object.keys(ChampionsData)
const randomKey = Math.floor(Math.random() * keys.length)
const champObject = ChampionsData[randomKey]
const champData = Object.values(champObject);

return(
<div> 
    {champData.map((value, index) => {      
      return <div key={index}>
        <ul>
        <li>{value.name}</li>
        <li>{value.title}</li>
        </ul>
      </div>
    })}
</div>
  )
 }
}
export default MainPage

我需要如何解决这个问题,这样我就不会丢失实际的属性名称?

标签: javascriptarraysjsonreactjs

解决方案


const arr = []
Object.keys(MyObject).forEach(key => arr.push({name: key, value: MyObject[key]}))

然后像这样访问:

console.log(arr[0].name, arr[0].value) //id, jarvaniv (I prefer Zac)

推荐阅读