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': { 'typ
Solution 1:
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 } };
functioniterate(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;
}
functionisArray(o) {
return o instanceofArray;
}
iterate(obj);
Solution 2:
Pass on the keys in the recursive call:
function iterate(obj, path = []) {
for (let propertyin obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], [...path, property]);
} else {
console.log(path, property , obj[property])
}
}
}
}
Post a Comment for "Javascript - Traverse Through The Json Object And Get Each Item Hierarchical Key Including Nested Objects And Arrays"