【问题标题】:Split data JSON after data in VueJS在 VueJS 中的数据之后拆分数据 JSON
【发布时间】:2020-03-06 16:46:12
【问题描述】:

如果数组后有数组,如何在 JSON 中拆分数据?这是我的 JSON 格式

{
    "status": "true",
    "error": "",
    "data": [
        {
            "id": 1,
            "sections": [
                {
                    "section_id": 1,
                    "position": []
                }
            ]
        }
     ]
}

所以,我正在使用 AXIOS 。此代码AXIOS

const url = '/api/v1/form/'
            axios
                .get(url)
                .then(response => {
                    this.listing = response.data.data;
                }) 

如何使用 response.data.data.sections 调用部分?我正在尝试,但错误未定义。请帮帮我谢谢

【问题讨论】:

  • well data 是一个数组,我怀疑你可以在没有索引的情况下使用它

标签: laravel vue.js axios


【解决方案1】:

response.data.data[0].sections

data 是根据您的 json 的数组,因此您不能直接调用部分,您必须在数组中迭代或选择一个实例。

以下代码应打印所有部分 id //未经测试的代码

const url = '/api/v1/form/'
            axios
                .get(url)
                .then(response => {
                    response.data.data.foreach((listing)=>{
                        console.log(listing.sections.section_id)
                    })
                }) 

如果您总是在data 下只有一个条目,或者您只想访问data 的第一个条目,您可以使用response.data.data[0].sections 这是一种不好的访问方式,因为如果数据为空,它将给你一个错误。如果情况是您在data 下只有一个条目,您应该将您的 json 更改为

{
"status": "true",
"error": "",
"data":
    {
        "id": 1,
        "sections": [
            {
                "section_id": 1,
                "position": []
            }
        ]
    }

}

然后您可以直接访问它response.data.data.sections,但只要它是一个数组,您就必须这样对待它。

遍历部分和位置 [根据 cmets]:

 const url = '/api/v1/form/'
            axios
                .get(url)
                .then(response => {
                    response.data.data.foreach((listing)=>{ //#this will get you each listing(parent object that contains sections array)
                        listing.sections.foreach((section)=>{//# this will get you each section(parent object that contains position array)
                           section.position.foreach((el)=>{//# this will get you each elment in the position array as `el`
                               console.log(el)
                           })
                        })

                    })
                }) 

【讨论】:

  • 如果循环 sectionposition,如何编写
  • for inside for 可以。你可以做很多事情,但 for 循环是 Array.foreach(function)
  • 我不明白,可以给我解释更多。谢谢
【解决方案2】:

试试这个:

const url = '/api/v1/form/'
axios
    .get(url)
    .then(response => {
        this.listing = response.data;
        console.log(this.listing.data) // <-------
    }) 

【讨论】:

  • 我知道,但是如何在数据中调用sections
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2021-09-16
  • 2018-09-01
相关资源
最近更新 更多