Created
June 22, 2015 21:31
-
-
Save linus-amg/6f5513b4ee1a0c74d917 to your computer and use it in GitHub Desktop.
nested-creator
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 source = { | |
'1': { name: 'Linus' }, | |
'2.1': { name: 'Raul' }, | |
'2.2': { name: 'Beto' }, | |
'2.3': { name: 'Alex' }, | |
'2.4': { name: 'Josue' }, | |
'3': { name: 'Florian' } | |
}; | |
function createObjects(parent, chainArray, value) { | |
if (chainArray.length == 1) { | |
parent[chainArray[0]] = value; | |
return parent; | |
} | |
else { | |
parent[chainArray[0]] = parent[chainArray[0]] || {}; | |
return createObjects(parent[chainArray[0]], chainArray.slice(1, chainArray.length), value); | |
} | |
} | |
var keys = Object.keys(source); | |
var result = {}; | |
for(var i = 0, l = keys.length; i < l; i++) { | |
createObjects(result, keys[i].split('.'), source[keys[i]]); | |
} | |
console.log(result); |
Author
linus-amg
commented
Jun 22, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment