json - 如何在反应js中访问json对象内的数组
问题描述
我正在尝试访问 json 对象内的数组。这是我的 json 文件。
{
"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 的值,但无法获取附件名称,它返回空?为什么无法从附件中获取值
解决方案
问题是因为您的附件是数组并且正在执行
attachmentList.slice(0, 1).map(item => item.name),
失败,因为 attachmentList 包含数组数组,而 item 是一个数组。
尝试使用flat,它将数组(附件)的数组展平为附件数组。
签出片段
var data = {
"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).flat(),
attachmentName = attachmentList.slice(0, 1).map(item => item.name),
createTime = items.slice(0, 1).map(item => item.createTime),
} = data;
console.log(attachmentName)
推荐阅读
- postfix-mta - 后缀 header_checks 一般理解但有更多问题
- asp.net-mvc-5 - 使用 Form-Control 类选择后 MVC 下拉列表不显示值
- javascript - 如何停止和播放猫头鹰轮播 onclick 项目
- php - 如何在 wordpress 页面中使用 $_GET
- android - 由于 TypeLoadException,Xamarin 和 OpenTK Android 无法启动
- c# - 如何仅为我的程序(c#,winform)在Windows 10中禁用“滚动非活动窗口”
- java - 什么是 StubRoutines::jbyte_disjoint_arraycopy
- azure - 连接到 Blob 存储“在配置中未找到它们的凭据”
- mdx - iccube中的MDX钻中级
- r - 当数据集中没有符合输入的观察值时,对闪亮的 selectizeInput 进行过滤并显示空白图