将JSON转换为数组打字稿

时间:2020-09-09 06:11:49

标签: javascript json angular typescript

我有这样的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过滤为某些属性,我具有属性 en test2 ,我的新对象应该像

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

我尝试了 help.en.test2 ,但出现错误 TypeError:无法读取未定义的属性“ test2”

任何人都可以帮助我重新映射,谢谢

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您应该尝试:help[0].en[0].test2

答案 2 :(得分:0)

诸如此类的问题很多。如果您在弄清某些JSON的结构时遇到麻烦,则可以使用chrome开发人员控制台。如果您将代码粘贴到chrome开发者控制台中,则可以使用test进行尝试。

仅看一下它,help是一个数组,因此help.en将是未定义的,您需要使用help[0].en

然后看,en是一个数组,因此help[0].en.test2也将是未定义的。您必须执行help[0].en[0].test2

当然这也是一个数组...