Skip to content

Instantly share code, notes, and snippets.

@anikets
Created September 7, 2018 06:52
Show Gist options
  • Save anikets/fabb3c557a4361459e4b500a0d8d589b to your computer and use it in GitHub Desktop.
Save anikets/fabb3c557a4361459e4b500a0d8d589b to your computer and use it in GitHub Desktop.
Iterate through all object properties recursively in JavaScript
// Traverse through all properties, including nested, in an object.
var obj = {
one: 1,
two: 'two',
three: [1,2,3],
four: {
four1: 1,
four2: true,
four3: {
four3_1: 'super',
four3_2: ['nested', 'stuff', {a: 123, b: 456}],
}
},
};
function iterateArray(arr, ancestor) {
console.log('iterateArray', arr);
for (var ac = 0; ac < arr.length; ac++) {
if (['boolean', 'number', 'string'].indexOf(typeof arr[ac]) >= 0) {
console.log(ancestor, '\t\t\t', arr[ac], '\t\t\t', typeof arr[ac]);
} else if (arr[ac].constructor === Array) {
ancestor.push(ac);
iterateArray(o[key], ancestor);
} else if (typeof arr[ac] === 'object') {
ancestor.push(ac);
traverse(arr[ac], ancestor);
}
}
}
function traverse(o, ancestor) {
console.info('traverse', o);
if (!ancestor) ancestor = [];
for (var key in o) {
if (['boolean', 'number', 'string'].indexOf(typeof o[key]) >= 0) {
console.log(ancestor, '\t\t\t', key, '\t\t\t', o[key], '\t\t\t', typeof o[key]);
} else if (o[key].constructor === Array) {
ancestor.push();
iterateArray(o[key], ancestor);
} else if (typeof o[key] === 'object') {
ancestor.push(key);
traverse(o[key], ancestor);
}
}
}
traverse(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment