【问题标题】:Iterate through an array of objects with deep nested objects and arrays遍历具有深层嵌套对象和数组的对象数组
【发布时间】:2020-04-13 21:28:03
【问题描述】:

我有一个从Collection > Folder/Request > Request 结构生成的 JSON 数组。

示例:

[
  {
    "name": "My Collection",
    "folders": [
      {
        "name": "bdg",
        "requests": [
          {
            "url": "https://reqres.in",
            "path": "/api/users",
            "method": "GET",
            "auth": "None",
            "httpUser": "",
            "httpPassword": "",
            "passwordFieldType": "password",
            "bearerToken": "",
            "headers": [],
            "params": [],
            "bodyParams": [],
            "rawParams": "",
            "rawInput": false,
            "contentType": "application/json",
            "requestType": "cURL",
            "name": "My Request",
            "collection": 0
          }
        ]
      }
    ],
    "requests": [
      {
        "url": "https://reqres.in",
        "path": "/api/users",
        "method": "GET",
        "auth": "None",
        "httpUser": "",
        "httpPassword": "",
        "passwordFieldType": "password",
        "bearerToken": "",
        "headers": [],
        "params": [],
        "bodyParams": [],
        "rawParams": "",
        "rawInput": false,
        "contentType": "application/json",
        "requestType": "cURL",
        "name": "My Request",
        "collection": 0
      }
    ]
  },
  {
    "name": "fndo",
    "folders": [
      {
        "name": "bdghg",
        "requests": [
          {
            "url": "https://reqres.in",
            "path": "/api/users",
            "method": "GET",
            "auth": "None",
            "httpUser": "",
            "httpPassword": "",
            "passwordFieldType": "password",
            "bearerToken": "",
            "headers": [],
            "params": [],
            "bodyParams": [],
            "rawParams": "",
            "rawInput": false,
            "contentType": "application/json",
            "requestType": "cURL",
            "name": "My Request",
            "collection": 1
          }
        ]
      }
    ],
    "requests": [
      {
        "url": "https://reqres.in",
        "path": "/api/users",
        "method": "GET",
        "auth": "None",
        "httpUser": "",
        "httpPassword": "",
        "passwordFieldType": "password",
        "bearerToken": "",
        "headers": [],
        "params": [],
        "bodyParams": [],
        "rawParams": "",
        "rawInput": false,
        "contentType": "application/json",
        "requestType": "cURL",
        "name": "My Request",
        "collection": 1
      }
    ]
  }
]

我想遍历这个 JSON 中的所有节点、数组和对象。 JSON 将由对象、对象数组和数组组成。

我尝试了Object.keys().map().forEach(),但在嵌套条件下失败了。

具有递归的 E6S 解决方案将成为救命稻草。

提前致谢!

【问题讨论】:

  • I tried - 展示您尝试过的内容,而不仅仅是引用您认为可以使用的方法。 SO 希望您实际上首先尝试解决自己的问题。另外,为什么需要递归?或者数据的深度可以超过 2 层吗?
  • 我一定错过了JSON.parse() 部分。是的,只有 2 级深度。

标签: javascript arrays json vue.js


【解决方案1】:

@codingspear 的答案正是我在寻找https://*.com/a/59441109/8335089

我能够用这个遍历所有节点:

      let collections = JSON.parse(myJson);
      for (let i = 0; i < collections.length; i++) {
        console.log("Collection", i + 1, collections[i].name);
        let folders = collections[i].folders;
        for (let i = 0; i < folders.length; i++) {
          console.log("Folder", i + 1, folders[i].name);
          let requests = collections[i].requests;
          for (let i = 0; i < requests.length; i++) {
            console.log("Request", i + 1, requests[i].name);
          }
        }
        let requests = collections[i].requests;
        for (let i = 0; i < requests.length; i++) {
          console.log("Request", i + 1, requests[i].name);
        }
      }

【讨论】:

    【解决方案2】:

    如果目标是将此 JSON 转换为对象,那么最好的解决方案是解析 JSON。例如:

    let myJson = "[
      {
        "name": "Collection 1",
      },
      {
        "name": "Collection 2",
      },
      {
        "name": "Collection 3",
      }
    ]"
    

    下一步是使用 JSON.parse() 函数

    let myObj = JSON.parse(myJson);
    

    现在您可以根据需要轻松循环播放

    for(let i = 0; i < myObj.length; i++){
      console.log(myObj[i].name);
    }
    

    或者直接访问任何属性

    let name1 = myObj[0].name;
    

    【讨论】:

    • 我想知道 ES6 中是否有任何替代循环方法可以实现更简洁的实现?无论如何,这是一个快速的答案,并且有效。谢谢。
    • myObj.foreach((element, index, self) =&gt; { consol.log(index + ": " + element.name) }
    • foreach 可能很方便,但你会失去continuebreak 的力量。 for of 也是一个选项 for(element of myObj){ consol.log(element.name) },但该索引再次非常方便,所以如果您需要它进行计算,那么我认为坚持使用。
    • 知道了。谢谢!
    最近更新 更多