Skip to content

Instantly share code, notes, and snippets.

@daniellizik
Last active January 16, 2016 04:42
Show Gist options
  • Save daniellizik/2eee8c7a279dc34720d3 to your computer and use it in GitHub Desktop.
Save daniellizik/2eee8c7a279dc34720d3 to your computer and use it in GitHub Desktop.
walks through object and generates hash where the key is the path with deliminator character and value
// https://jsfiddle.net/dlizik/x40fv8rk/
function treewalk(obj, bucket, pathStr, delim) {
var i, p, last = pathStr.slice(0, pathStr.length - 1);
if (Array.isArray(obj)) {
if (obj.length === 0)
bucket[last] = obj;
else {
for (i = 0; i < obj.length; i++)
treewalk(obj[i], bucket, pathStr + i + delim, delim)
}
}
else if (Object.prototype.toString.call(obj) === '[object Object]') {
if (Object.keys(obj).length === 0)
bucket[last] = obj;
else {
for (p in obj)
treewalk(obj[p], bucket, pathStr + p + delim, delim);
}
}
else if (typeof obj === 'number' || typeof obj === 'string' || obj === null)
bucket[last] = obj;
else if (obj === undefined)
throw new Error('cannot pass undefined');
return bucket;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment