Created
November 2, 2023 06:54
-
-
Save nixjs/84957208fb09b6925da9dae5d2824c32 to your computer and use it in GitHub Desktop.
Convert javascript dot notation object to nested object
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
const obj = { | |
"start.headline": "1 headline", | |
"start.subHeadline": "subHeadline", | |
"start.accordion.headline": "2 headline", | |
"start.accordion.sections.0.content": "content 0", | |
"start.accordion.sections.0.iconName": "icon 0", | |
"start.accordion.sections.1.headline": "headline 1", | |
"start.accordion.sections.1.content": "content 1", | |
"start.accordion.sections.1.iconName": "icon 1", | |
"start.accordion.sections.2.headline": "headline 2", | |
"start.accordion.sections.2.content": "content 2", | |
"start.accordion.sections.2.iconName": "icon 2", | |
"end.field": "add headline", | |
"end.button": "add button", | |
"end.msgs.success": "success msg", | |
"end.msgs.error": "error msg", | |
}; | |
const res = Object.keys(obj).reduce((res, key) => { | |
const path = key.split('.'); | |
const lastIndex = path.length - 1; | |
path.reduce( | |
(acc, k, i, a) => acc[k] = lastIndex === i ? | |
obj[key] : | |
acc[k] || (/\d/.test(a[i+1]) ? [] : {}), | |
res | |
); | |
return res; | |
}, {}); | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment