gpt4 book ai didi

json - 使用react获取json对象数据

转载 作者:行者123 更新时间:2023-12-03 13:58:19 25 4
gpt4 key购买 nike

我正在尝试像这样从 json 中提取数据,该数据作为“值”导入

{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}

我正在使用.map,如下所示,但收到错误.default.map不是函数我相信这是因为我有对象而不是数组,我已经尝试了很多东西,包括 object.keys 但我到处都遇到错误,任何方向将不胜感激。

import values from './sample.json'

const vals = values.map((myval, index) => {
const items = person.items.map((item, i) => {

return (
<div>{item.name}</div>
)
})

return (
<div>{items}</div>
)
})

最佳答案

我认为您的数据和代码有一些错误。但是,在修复这些问题并将名称从“person”更改为“people”(如果这就是您想要的)之后,下面是执行您想要执行的操作的代码:

var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
},
};

var App = React.createClass({
render: function () {
var people = data.content.people.map(function (person) {
return <div>{person.name}</div>;
});

return <div>{people}</div>;
},
});

ReactDOM.render(<App />, document.getElementById("app"));

这是 JSBin:https://jsbin.com/coyalec/2/edit?html,js,output

更新:我正在用更详细的示例更新答案。它现在更通用地处理数据,就像它不假设“内容”等条目是什么,但它知道“人”或“宠物”等每种类型都是一个数组。

var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
pets: [
{
name: "Sweety",
age: 3,
},
{
name: "Kitty",
age: 5,
},
],
},
};

var App = React.createClass({
render: function () {
// Get the keys in data.content. This will return ['people', 'pets']
var contentKeys = Object.keys(data.content);

// Now start iterating through these keys and use those keys to
// retrieve the underlying arrays and then extract the name field
var allNames = contentKeys.map((t) =>
data.content[t].map((e) => <div>{e.name}</div>)
);

return <div>{allNames}</div>;
},
});

ReactDOM.render(<App />, document.getElementById("app"));

这是最新的 JSBin:https://jsbin.com/coyalec/4/edit?html,js,output

关于json - 使用react获取json对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38886131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com