Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active February 4, 2021 15:01
Show Gist options
  • Save ahallora/9731d73efb15bd3d3db647efa3389c12 to your computer and use it in GitHub Desktop.
Save ahallora/9731d73efb15bd3d3db647efa3389c12 to your computer and use it in GitHub Desktop.
Convert string in dot notation into an object with JavaScript
const dotPathToObject = (pathStr, value) => pathStr
.split(".")
.reverse()
.reduce((acc, cv, index) => ({
[cv]: index === 1 && value ? {[acc]: value} : acc
}))
console.log("expect:", JSON.stringify({
"a": {
"b": {
"c": {
"d": "e"
}
}
}
}
));
console.log("return:", JSON.stringify(
dotPathToObject("a.b.c.d", "e")
))
/*
expect: {"a":{"b":{"c":{"d":"e"}}}}
return: {"a":{"b":{"c":{"d":"e"}}}}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment