【问题标题】:Convert JSON to array typescript将 JSON 转换为数组打字稿
【发布时间】:2020-12-27 12:50:47
【问题描述】:

我有一些这样的 json

 const help = [
      {
        "en": [
          {
            "test2": [
              {
                "title": "Naslov1",
                "subtitle": "Podnaslov1",
                "answers": [
                  {
                    "answer": "Odgovor 11"
                  },
                  {
                    "answer": "Odgovor 12"
                  }
                ]
              }
            ],
            "test1": [
              {
                "title": "Naslov2",
                "subtitle": "Podnaslov2",
                "answers": [
                  {
                    "answer": "Odgovor 21"
                  },
                  {
                    "answer": "Odgovor 22"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]

我需要将此 json 过滤到某个属性,我有属性 entest2 我的新对象应该看起来像

const newArray =  [ {
                    "title": "Naslov1",
                    "subtitle": "Podnaslov1",
                    "answers": [
                      {
                        "answer": "Odgovor 11"
                      },
                      {
                        "answer": "Odgovor 12"
                      }
                    ]
                  }]

我已尝试 help.en.test2,但出现错误 TypeError: Cannot read property 'test2' of undefined

谁能帮我重新映射一下,谢谢

【问题讨论】:

标签: javascript json angular typescript


【解决方案1】:

您需要使用help[0].en[0].test2,因为helpen 是一个数组,您的数据位于索引0。

【讨论】:

    【解决方案2】:

    你应该试试:help[0].en[0].test2

    【讨论】:

      【解决方案3】:

      这样的问题有很多。如果您在弄清楚某些 JSON 的结构时遇到问题,使用 chrome 开发者控制台会有所帮助。如果您将代码粘贴到 chrome 开发控制台中,您可以尝试使用 test

      看一看,help是一个数组,所以help.en是未定义的,需要使用help[0].en

      然后看,en 是一个数组,所以help[0].en.test2 也将是未定义的。你必须做help[0].en[0].test2

      当然那也是一个数组……

      【讨论】:

        猜你喜欢
        • 2018-06-14
        • 2018-04-26
        • 2021-12-19
        • 2016-09-10
        • 2018-09-18
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多