Skip to content

Instantly share code, notes, and snippets.

@Kinjalrk2k
Last active May 28, 2021 12:41
Show Gist options
  • Save Kinjalrk2k/2cbf466aa3f4d8dec7a64588da86acdb to your computer and use it in GitHub Desktop.
Save Kinjalrk2k/2cbf466aa3f4d8dec7a64588da86acdb to your computer and use it in GitHub Desktop.
Convert a Flat Object to a nested Object in JavaScript
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