如何在react js中访问json对象内的数组
我试图访问json对象中的数组。这是我的json文件如何在react js中访问json对象内的数组,json,reactjs,Json,Reactjs,我试图访问json对象中的数组。这是我的json文件 { "items": [ { "createTime": "2019-10-25T04:33:50.238Z", "attachments": [ { "name": "xxx.pdf", "legal": false, "id": "1908925450",
{
"items": [
{
"createTime": "2019-10-25T04:33:50.238Z",
"attachments": [
{
"name": "xxx.pdf",
"legal": false,
"id": "1908925450",
"abc": true,
"def": true
},
{
"name": "xxx_original.xml",
"legal": true,
"id": "1908925449",
"abc": false,
"def": false
}
]
}
]
}
我使用以下代码访问此处包含的详细信息
const {
items = [],
attachmentList = items.slice(0, 1).map(item => item.attachments),
attachmentName = attachmentList.slice(0, 1).map(item => item.name),
createTime = items.slice(0, 1).map(item => item.createTime),
} = data;
我可以获取createTime的值,但无法获取attachmentName,它返回空?为什么无法从附件获取值。0、1将返回一个新数组。因此,当您使用map时,attachmentList将在数组中返回一个数组,如下所示:
[{…}]
0:
attachments: (2) [{…}, {…}]
createTime: "2019-10-25T04:33:50.238Z"
首先,您可以像这样重构:
const {
items = [],
attachmentList = items.slice(0, 1)[0].map(item => item.attachments),
// Access to the first item with return of items.slice(0, 1)
attachmentName = attachmentList.slice(0, 1).map(item => item.name),
createTime = items.slice(0, 1).map(item => item.createTime),
} = data;
或:
这个问题是因为您的附件是数组并且正在运行 attachmentList.0,1.mapitem=>item.name 失败,因为attachmentList包含数组数组,而项是数组 尝试使用,它会将数组附件数组展平到数组附件 签出代码段 风险值数据={ 项目:[{ 创建时间:2019-10-25T04:33:50.238Z, 附件:[{ 姓名:xxx.pdf, 法律:错, id:1908925450, abc:是的, def:是的 }, { 名称:xxx_original.xml, 法律:是的, id:1908925449, abc:错, def:错 } ] }] } 常数{ 项目=[], attachmentList=items.slice0,1.mapitem=>item.attachments.flat, attachmentName=attachmentList.0,1.mapitem=>item.name, createTime=items.0,1.mapitem=>item.createTime, }=数据;
logattachmentName这是因为您的attchmentList现在是一个数组数组,您可以这样做来获取名称
const {
items = [],
attachmentList = items.slice(0, 1).map(item => item.attachments),
attachmentName = attachmentList.slice(0, 1).map((item, i) => item[i].name),
createTime = items.slice(0, 1).map(item => item.createTime),
} = data;
希望有帮助这是你想要的吗@VahidAkhtar我想要一种访问数据的方法。因为我访问attachmentList的方式与访问items数组的方式相同。。
const {
items = [],
attachmentList = items.slice(0, 1).map(item => item.attachments),
attachmentName = attachmentList.slice(0, 1).map((item, i) => item[i].name),
createTime = items.slice(0, 1).map(item => item.createTime),
} = data;