Created
January 2, 2011 01:55
-
-
Save penguinboy/762197 to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
This file contains 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
var flattenObject = function(ob) { | |
var toReturn = {}; | |
for (var i in ob) { | |
if (!ob.hasOwnProperty(i)) continue; | |
if ((typeof ob[i]) == 'object') { | |
var flatObject = flattenObject(ob[i]); | |
for (var x in flatObject) { | |
if (!flatObject.hasOwnProperty(x)) continue; | |
toReturn[i + '.' + x] = flatObject[x]; | |
} | |
} else { | |
toReturn[i] = ob[i]; | |
} | |
} | |
return toReturn; | |
}; |
@danzelbel like a charm!
Jewel!
This is my implementation, it just flattens every object in the parent object into one, without keying them with object.key
.
Working example
Code:
function flatten(obj = {}) {
const doneObject = {}
for (const [k, v] of Object.entries(obj)) {
if (typeof v == "object" && !(v instanceof Date) && !Array.isArray(v) && !(v instanceof regExp)) {
Object.assign(doneObject, flatten(v))
} else {
doneObject[k] = v
}
}
return doneObject
}
Thank you for the original implementation!
A version that leaves undefined behind, array as is and don't try to flatten primitive objects (Number, Boolean, BigInt and String essentially) :
const flatten = <T extends Record<string, any>>(object: T, path?: string): Record<string, any> =>
Object.entries(object).reduce((acc, [key, val]) => {
if (val === undefined) return acc;
if (path) key = `${path}.${key}`;
if (typeof val === 'object' && val !== null && !(val instanceof Date) && !(val instanceof RegExp) && !Array.isArray(val)) {
if (val !== val.valueOf()) {
return { ...acc, [key]: val.valueOf() };
}
return { ...acc, ...flatten(val, key) };
}
return { ...acc, [key]: val };
}, {});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you are the best!