Skip to content

Instantly share code, notes, and snippets.

@lyyourc
Created October 9, 2019 06:15
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 lyyourc/b913390c1c41ccdc7c52610e8c40458f to your computer and use it in GitHub Desktop.
Save lyyourc/b913390c1c41ccdc7c52610e8c40458f to your computer and use it in GitHub Desktop.
function nestStringProperties(obj) {
if (!obj) {
return {};
}
const isPlainObject = obj => !!obj && obj.constructor === {}.constructor;
const getNestedObject = obj => Object.entries(obj).reduce((result, [prop, val]) => {
prop.split('.').reduce((nestedResult, prop, propIndex, propArray) => {
const lastProp = propIndex === propArray.length - 1;
if (lastProp) {
nestedResult[prop] = isPlainObject(val) ? getNestedObject(val) : val;
} else {
nestedResult[prop] = nestedResult[prop] || {};
}
return nestedResult[prop];
}, result);
return result;
}, {});
return getNestedObject(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment