Created
February 19, 2019 12:56
-
-
Save postman31/601d7bb36bd8a6e08e92390ef6044c0a to your computer and use it in GitHub Desktop.
string to nested object
This file contains hidden or 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 plain = { | |
'data.analytics.name': 'coehn', | |
'data.analytics.role': 'ninja' | |
} | |
var converted = function (plainObj) { | |
var converted = {} | |
for (var plainKey in plainObj) { | |
var nextStep = converted | |
var splitted = plainKey.split('.') | |
for (var i in splitted) { | |
var level = splitted[i] | |
nextStep[level] = nextStep[level] || {} | |
if (i == splitted.length - 1 ) { | |
nextStep[level] = plainObj[plainKey] | |
} else { | |
nextStep = nextStep[level] | |
} | |
} | |
} | |
return converted | |
} | |
console.log(JSON.stringify(converted(plain), null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment