Last active
May 28, 2021 12:41
-
-
Save Kinjalrk2k/2cbf466aa3f4d8dec7a64588da86acdb to your computer and use it in GitHub Desktop.
Convert a Flat Object to a nested Object in JavaScript
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
const flatToNestedObject = (obj) => { | |
let nestedObj = {}; | |
for (let key in obj) { | |
const value = obj[key]; | |
if (key.indexOf(".") >= 0) { | |
const nestedKeys = key.split("."); | |
const parent = nestedKeys.shift(); | |
const child = nestedKeys.join("."); | |
nestedObj[parent] = { ...nestedObj[parent] }; | |
nestedObj[parent][child] = value; | |
nestedObj[parent] = flatToNestedObject(nestedObj[parent]); | |
} else { | |
if (typeof value === "object") { | |
nestedObj[key] = flatToNestedObject(value); | |
} else { | |
nestedObj[key] = value; | |
} | |
} | |
} | |
return nestedObj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment