Skip to content

Instantly share code, notes, and snippets.

@postman31
Created February 19, 2019 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postman31/601d7bb36bd8a6e08e92390ef6044c0a to your computer and use it in GitHub Desktop.
Save postman31/601d7bb36bd8a6e08e92390ef6044c0a to your computer and use it in GitHub Desktop.
string to nested object
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