Last active
December 11, 2020 12:10
-
-
Save peter/0479fcfaf0cde407cba30ddeb8f941ea to your computer and use it in GitHub Desktop.
Traverse an object in Node.js/Javascript with a generator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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