Last active
February 4, 2021 15:01
-
-
Save ahallora/9731d73efb15bd3d3db647efa3389c12 to your computer and use it in GitHub Desktop.
Convert string in dot notation into an object with JavaScript
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
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