Skip to content

Instantly share code, notes, and snippets.

@technikhil314
Last active May 4, 2022 05:29
Show Gist options
  • Save technikhil314/1aa12b8f551f3c3be0db9dd4ee615ca0 to your computer and use it in GitHub Desktop.
Save technikhil314/1aa12b8f551f3c3be0db9dd4ee615ca0 to your computer and use it in GitHub Desktop.
Flatten javascript object
let o = {
k: 10,
a: {
b: {
c: ["10", "20"]
},
},
d: {
e: 20
},
f: "30",
g: {
h: {
i: {
j: "40"
}
}
}
}
let flatObject = {};
let originalObject = null;
function flattenObject(o, key = "") {
for (let prop in o) {
const type = typeof o[prop];
if (type !== "object" || Array.isArray(o[prop])) {
// if the value is string add it to flat object as a.b: 10
flatObject[key + prop] = o[prop];
} else {
// if its a nested object modify the key and recurse
key += prop + ".";
flattenObject(o[prop], key);
}
}
return flatObject;
}
console.log(flattenObject(o));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment