Last active
May 4, 2022 05:29
-
-
Save technikhil314/1aa12b8f551f3c3be0db9dd4ee615ca0 to your computer and use it in GitHub Desktop.
Flatten javascript object
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
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