首页 > 解决方案 > 如何在反应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 的值,但无法获取附件名称,它返回空?为什么无法从附件中获取值

标签: jsonreactjs

解决方案


问题是因为您的附件是数组并且正在执行

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)


推荐阅读