Skip to content

Instantly share code, notes, and snippets.

@markgarrigan
Created November 1, 2021 18:31
Show Gist options
  • Save markgarrigan/e252a5357b4bdcb2bdafdcfb390cf4fd to your computer and use it in GitHub Desktop.
Save markgarrigan/e252a5357b4bdcb2bdafdcfb390cf4fd to your computer and use it in GitHub Desktop.
Convert dot notation keys to object keys
const util = require('util')
const obj = {
"city": "De Pere",
"foo.hoo": "loo",
"foo.bar.name": "mark",
"foo.bar.age": 10,
"foo.bar.color": "larry",
"foo.bar.house.number": 523,
}
const newObj = Object.keys(obj).reduce((acc, result, ci) => {
const keys = result.split('.')
const top = acc[keys[0]] || {}
acc[keys[0]] = keys.reduce((acc2, result2, ci2) => {
if (keys.length == 1) {
acc2 = obj[keys[0]]
return acc2
} else if (ci2 == keys.length - 1) {
acc2[result2] = obj[result]
return top
} else if (ci2 == 0) {
return acc2
} else {
acc2[result2] = acc2[result2] || {}
return acc2[result2]
}
}, top)
return acc
}, {})
console.log(util.inspect(newObj, { showHidden: false, depth: null, colors: true }))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment