Skip to content

Instantly share code, notes, and snippets.

@nwrox
Created August 30, 2017 17:42
Show Gist options
  • Save nwrox/617bd7c319a4d9e91bb7c9a3301a1718 to your computer and use it in GitHub Desktop.
Save nwrox/617bd7c319a4d9e91bb7c9a3301a1718 to your computer and use it in GitHub Desktop.
const arrStr = 'a.b.c.d'.split('.')
const res = arrStr.reduce((acc, curr, i, j) => {
acc.push({ [`${curr}`]: {} })
return acc
}, []).reduce((acc, curr, i, arr) => {
acc = arr[0]
if(i < arr.length) {
arr[i][Object.keys(arr[i])] = arr[i+1]
}
if(i === arr.length - 2) {
const key = Object.keys(arr[i+1])
arr[i][Object.keys(arr[i])] = { [`${key}`]: {} }
}
return acc
}, {})
console.log(JSON.stringify(res, null, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment