在对象名称中使用连字符对嵌套数组进行迭代

时间:2018-07-04 18:57:23

标签: arrays json angular typescript iterator

首先,我知道用连字符命名数组对象是完全不正确的,而且我不是它的创建者。我需要在服务中调用API,并且许多对象的命名不正确,例如{"children-education": [{ "Kid Stories": [

我尝试将名称分配给变量let edChild = "child-education",然后将其解析为对象,例如edChild = JSON.parse(edChild),但无济于事。我真的不知道自己在做什么,甚至也不可能这样做。

我可以选择致电我的客户,并请他的团队将对象重命名为比特殊字符愚蠢的对象,这比我无法在Typescript中调用的对象愚蠢,但我想了解是否存在一种在以后的场合或如果他们无法重命名的方法。

这是我要遍历的JSON示例:

{
    "business":
    [
        {
            "anim":
            [
                {
                    "child-education": [
                        {
                            "Kid Stories": [

                                {
                                    "id": 1,
                                    "name": "Three Little Pinkies",
                                    "url": "#",
                                    "description": "shows how the world is beautiful"
                                },
                  (... and so on)

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用JSON.parse()

像任何JSON字符串一样解析该JSON字符串

let str = "{\n" +
  "    \"business\":\n" +
  "    [\n" +
  "        {\n" +
  "            \"anim\":\n" +
  "            [\n" +
  "                {\n" +
  "                    \"child-education\": [\n" +
  "                        {\n" +
  "                            \"Kid Stories\": [\n" +
  "\n" +
  "                                {\n" +
  "                                    \"id\": 1,\n" +
  "                                    \"name\": \"Three Little Pinkies\",\n" +
  "                                    \"url\": \"#\",\n" +
  "                                    \"description\": \"shows how the world is beautiful\"\n" +
  "                                }]}]}]}]}" +
  ""
console.log(JSON.parse(str));

之后,您可以使用bracket notation访问任何属性名称

let str = "{\n" +
  "    \"business\":\n" +
  "    [\n" +
  "        {\n" +
  "            \"anim\":\n" +
  "            [\n" +
  "                {\n" +
  "                    \"child-education\": [\n" +
  "                        {\n" +
  "                            \"Kid Stories\": [\n" +
  "\n" +
  "                                {\n" +
  "                                    \"id\": 1,\n" +
  "                                    \"name\": \"Three Little Pinkies\",\n" +
  "                                    \"url\": \"#\",\n" +
  "                                    \"description\": \"shows how the world is beautiful\"\n" +
  "                                }]}]}]}]}" +
  ""
const obj = JSON.parse(str);

console.log(obj.business[0].anim[0]['child-education'][0]['Kid Stories'][0]);