Last active
January 2, 2016 10:49
-
-
Save chrisallenlane/8292452 to your computer and use it in GitHub Desktop.
This function parses a string representation of an object (written in dot notation) into an actual object.
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
#!/usr/bin/env node | |
// Parses a string representation of a nested object (of arbitrary depth) into | |
// a "proper" object. | |
function vivify(str) { | |
return str.split('.').reduceRight(function(a, b) { | |
var c = {}; | |
if (typeof a === 'string') { | |
var x = {}; | |
x[a] = {}; | |
c[b] = x; | |
} | |
else { | |
c[b] = a; | |
} | |
return c; | |
}); | |
} | |
// A String representation of an object that we'd like to vivify: | |
var dots = 'one.two.three.four'; | |
// Vivify | |
console.log(vivify(dots)); | |
// Outputs: { one: { two: { three: { four: {} } } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment