Skip to content

Instantly share code, notes, and snippets.

@peter
Last active December 11, 2020 12:10
Show Gist options
  • Save peter/0479fcfaf0cde407cba30ddeb8f941ea to your computer and use it in GitHub Desktop.
Save peter/0479fcfaf0cde407cba30ddeb8f941ea to your computer and use it in GitHub Desktop.
Traverse an object in Node.js/Javascript with a generator function
function isObject (value) {
return value != null && typeof value === 'object' && value.constructor === Object
}
//////////////////////////////////////////
// GENERATOR
//////////////////////////////////////////
function * traverseObj (value, path = []) {
yield [value, path]
if (Array.isArray(value) || isObject(value)) {
for (const [k, v] of Object.entries(value)) {
yield * traverseObj(v, [...path, k])
}
}
}
for (const [value, path] of traverseObj({foo: {bar: [1, 2, 3]}})) { console.log(value, path) }
// =>
// { foo: { bar: [ 1, 2, 3 ] } } []
// { bar: [ 1, 2, 3 ] } [ 'foo' ]
// [ 1, 2, 3 ] [ 'foo', 'bar' ]
// 1 [ 'foo', 'bar', '0' ]
// 2 [ 'foo', 'bar', '1' ]
// 3 [ 'foo', 'bar', '2' ]
//////////////////////////////////////////
// CALLBACK
//////////////////////////////////////////
function traverseObj (value, callback, path = []) {
callback(value, path)
if (Array.isArray(value) || isObject(value)) {
for (const [k, v] of Object.entries(value)) {
traverseObj(v, callback, [...path, k])
}
}
}
traverseObj({foo: {bar: [1, 2, 3]}}, (value, path) => { console.log(value, path) })
// =>
// { foo: { bar: [ 1, 2, 3 ] } } []
// { bar: [ 1, 2, 3 ] } [ 'foo' ]
// [ 1, 2, 3 ] [ 'foo', 'bar' ]
// 1 [ 'foo', 'bar', '0' ]
// 2 [ 'foo', 'bar', '1' ]
// 3 [ 'foo', 'bar', '2' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment