【发布时间】:2019-11-22 07:43:55
【问题描述】:
我有一个包含英雄联盟冠军信息的大型本地 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
我需要如何处理,以免丢失实际的属性名称?
【问题讨论】:
标签: javascript arrays json reactjs