简体   繁体   中英

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

{
  "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

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

"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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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