-
-
Save eivindingebrigtsen/2488917 to your computer and use it in GitHub Desktop.
Make tree structure from map 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
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; | |
}; |
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
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