Skip to content

Instantly share code, notes, and snippets.

@bgstaal
Created April 25, 2012 10:38
Show Gist options
  • Save bgstaal/2488889 to your computer and use it in GitHub Desktop.
Save bgstaal/2488889 to your computer and use it in GitHub Desktop.
Make tree structure from map object
var tree = function(map)
{
var treeStructure = {};
var names;
var name;
var i;
var numNames;
var currentObject = treeStructure;
var lastIndex;
if (map)
{
for (var key in map)
{
var value = map[key];
names = key.split(".");
numNames = names.length;
lastIndex = numNames-1;
currentObject = treeStructure;
for (i = 0; i < numNames; ++i)
{
name = names[i];
if (i == lastIndex)
{
currentObject[name] = value;
}
else if (!currentObject[name])
{
currentObject[name] = {};
}
currentObject = currentObject[name];
}
}
}
return treeStructure;
};
var myTree = tree(
{
"user.name.first": "ola",
"user.name.last": "normann",
"user.age": 34,
"user.bodyparts.arm.tattoes": ["snake", "anchor", "heart"]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment