Pavan Vidusankha
Pavan Vidusankha

Reputation: 23

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"

Upvotes: 0

Views: 789

Answers (2)

shrys
shrys

Reputation: 5960

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

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138437

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])
       }
     }
   }  
 }

Upvotes: 0

Related Questions