Created
January 27, 2021 18:25
-
-
Save PopeFelix/723ca75c0f9e910e948ea52e76bd1c28 to your computer and use it in GitHub Desktop.
This file contains 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
// A sketch demonstrating a way to take "/" delimited paths (e.g. '/foo/bar', '/foo/baz', '/foo/bak/quux', '/foo/bak/quuy') | |
// and put them into a single object where the keys match the path hierarchy. | |
const pathVals = { '/foo/bar/baz': 1, '/foo/bar/bak': 2, '/foo/quux': 11, '/alpha': 13 } | |
// Expected: | |
//{ | |
// foo: { | |
// bar: { | |
// baz: 1, | |
// bak: 2, | |
// }, | |
// quux: 11 | |
// }, | |
// alpha: 13 | |
//} | |
let obj = {} | |
const paths = Object.keys(pathVals) | |
for (let path of paths) { | |
const val = pathVals[path] | |
let bits = path.split('/').slice(1) | |
let ptr = obj | |
console.log({bits}) | |
for (let i = 0; i < bits.length; i++) { | |
let bit = bits[i] | |
if (i === (bits.length - 1)) { | |
ptr[bit] = val | |
} else { | |
if (!ptr[bit]) { | |
ptr[bit] = {} | |
} | |
ptr = ptr[bit] | |
} | |
} | |
console.log(JSON.stringify({path, obj, ptr}, null, 2)) | |
} | |
console.log(JSON.stringify({obj}, null, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment