简体   繁体   English

Javascript - 遍历 Json 对象并获取每个项目的分层键,包括嵌套对象和数组

[英]Javascript - Traverse through the Json Object and get each item hierarchical key including nested objects and arrays

I want to get the values and keys including these as to any JSON objects as a generic method to use even for the complex objects我想获取任何 JSON 对象的值和键,包括这些作为通用方法,甚至用于复杂对象

json json

{
  "timezone": 5.5,
  "schedule": {
    "type": "daily",
    "options": {
      "hour": 10,
      "minute": 29
    }
  }

want the values and keys in hierarchical schema just like these想要分层架构中的值和键就像这些

timezone - 5.5
schedule.type - daily
schedule.type.options.hour - 10
schedule.type.options.minute - 29

Also, I used this function can get the JSON objects all objects keys and values even in the nested arrays and objects in that此外,我使用这个函数可以获得 JSON 对象的所有对象键和值,即使在嵌套数组和对象中

function iterate(obj) {
  for (var property in obj) {
      if (obj.hasOwnProperty(property)) {
          if (typeof obj[property] == "object") {
              iterate(obj[property]);
          } else {
            console.log(property , obj[property])
          }
      }
  }
  return obj;
}

PS - Also I want to use this for arrays also PS - 我也想将它用于数组

"dirs": [ { "watchDir": "Desktop/logs", "compressAfterDays": 50 }, { "watchDir": "Desktop/alerts", "timeMatchRegex": "(.*)(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})_(\\d{2})(.*)", }]

the output I want to be just like this我想要的输出是这样的

dirs[0].watchdir="Desktop/alerts"
dirs[1].watchDir="Desktop/logs"

Pass on the keys in the recursive call:传递递归调用中的键:

 function iterate(obj, path = []) {
   for (let property in obj) {
     if (obj.hasOwnProperty(property)) {
       if (typeof obj[property] == "object") {
          iterate(obj[property], [...path, property]);
       } else {
         console.log(path, property , obj[property])
       }
     }
   }  
 }

 const obj = { "timezone": 5.5, "dirs": [ { "watchDir": "Desktop/logs", "compressAfterDays": 50 }, { "watchDir": "Desktop/alerts", "timeMatchRegex": "(.*)(\\\\d{4})-(\\\\d{2})-(\\\\d{2})-(\\\\d{2})_(\\\\d{2})(.*)", }] ,"schedule": { "type": "daily", "options": { "hour": 10, "minute": 29 }, 'available': true } }; function iterate(obj, str) { let prev = ''; for (var property in obj) { if (obj.hasOwnProperty(property)) { if (typeof obj[property] == "object") { const s = isArray(obj) ? prev + str + '[' + property + ']' + '.' : prev + property + (isArray(obj[property]) ? '' : '.'); iterate(obj[property], s); } else { prev = (str != undefined ? str : ''); console.log(prev + property, '- ' + obj[property]); } } } return obj; } function isArray(o) { return o instanceof Array; } iterate(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM