Skip to content

Instantly share code, notes, and snippets.

@nixjs
Created November 2, 2023 06:54
Show Gist options
  • Save nixjs/84957208fb09b6925da9dae5d2824c32 to your computer and use it in GitHub Desktop.
Save nixjs/84957208fb09b6925da9dae5d2824c32 to your computer and use it in GitHub Desktop.
Convert javascript dot notation object to nested object
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