如何在React JS中访问JSON对象内的数组

时间:2019-10-25 06:00:40

标签: json reactjs

我正在尝试访问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的值,但是无法获取attachmentName,它返回空值?为什么无法从附件获取值

3 个答案:

答案 0 :(得分:1)

问题是因为您的附件是数组并且在做

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)

答案 1 :(得分:0)

items.slice(0, 1)将返回一个新的数组。因此,当您使用map时,attachmentList将在Array中返回一个Array,如下所示:

[{…}]
   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;

或者:

const {
        items = [],
        attachmentList = items.slice(0, 1).map(item => item.attachments),
        attachmentName = attachmentList[0].slice(0, 1).map(item => item.name),
        // Access to the first item of attachmentList
        createTime = items.slice(0, 1).map(item => item.createTime),
    } = data;

答案 2 :(得分:0)

这是因为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;

希望有帮助