我正在读取两个 JSON 文件,只有读取一个文件后,我才会知道另一个文件的子文件。
示例:
文件:“/user.js”
{Users:[name: "John", profession: "writer"],[name: "May", profession: "none"]}
文件:“/ages.js”
{ages:{Jack:{age:66}},{John:{age:45}}}
render(){
<div>
First Worker {Users[0].name} <!-- Only now I will know his name-->
Is {ages.X.age} years old <!-- X should be John, I wanted to do something like {ages.Users[0].name.age} -->
</div>
}
最佳答案
文件:“/user.js”和“/ages.js”不是有效的 JSON 文件,让我们在 https://jsonlint.com 进行检查。 .
有效的 JSON 文件可能是:
文件:“/user.js”
{"Users": [{"name": "John","profession": "writer"},{"name": "May","profession": "none"}]}
文件:“/ages.js”
{"ages": [{"Jack": {"age": 66}},{"John": {"age": 45}}]}
更改后,cowCrazy 的解决方案应该可以工作。
在 JavaScript 中,您可以将对象的键值作为关联数组进行访问,让我们看一下这个示例:
var users = {"name":"cowCrazy"};
var tmp = "name";
console.log(users.name);
console.log(users["name"]);
console.log(users[tmp]);
三个console.log将显示相同的结果:“cowCrazy”。
希望这对您有帮助。
关于javascript - 如何在 React 中渲染相互关联的单独 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47607445/