Skip to content

Instantly share code, notes, and snippets.

@chrisallenlane
Last active January 2, 2016 10:49
Show Gist options
  • Save chrisallenlane/8292452 to your computer and use it in GitHub Desktop.
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.
#!/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