Created
October 9, 2019 06:15
-
-
Save lyyourc/b913390c1c41ccdc7c52610e8c40458f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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