【发布时间】:2020-06-24 10:25:46
【问题描述】:
我是一个 Reactjs 菜鸟,并且有一个具有以下结构的对象。在我的功能组件中,我想使用最现代的方法来遍历对象层次结构中顶层的键(即 A、B、C)并显示与“名称”键关联的值。
data.json
{
"A": {
"name": "AA",
"type": "AB",
"values": [
["AC", "AD", "AE"],
["AF", "AG", "AH"]
]
},
"B": {
"name": "BA",
"type": "BB",
"values": [
["BC", "BD", "BE"],
["BF", "BG", "BH"]
]
},
"C": {
"name": "CA",
"type": "CB",
"values": [
["CC", "CD", "CE"],
["CF", "CG", "CH"]
]
}
}
我想要的结果是在屏幕上显示以下内容:
A - AA
B - BA
C - CA
我曾尝试使用 map 函数来执行此操作,但后来我读到该 map 仅适用于数组,而不适用于对象?我也尝试过这个答案:https://stackoverflow.com/a/14810722/679841 但我意识到(a)我无法让它在我的情况下工作,可能是因为我的对象有点复杂而且我对此并不陌生,并且(b) 有一些更新让我想知道现在是否有更好的方法?
这是我的功能组件的简化版本。
FunctionalComponent.js
import React from 'react';
import Data from './data.json'; //See above for content of this json file
const data= Data; //not sure if this is necessary?!
function Loop(){
<form>
return(
//This is where I want to start my loop and dynamically populate
<div>{data.A.name} - {data.A.name}</div>
//This is where I want to end the loop
);
</form>
}
export default Loop;
任何帮助实现我想要的结果将不胜感激。
非常感谢,
凯蒂
【问题讨论】:
-
Object.entries(obj).map(([key, value]) => ({key: key, value: value.name}) )