Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inspired from gdibble
function flattenObject(ob) {
let toReturn = {};
let flatObject;
for (let i in ob) {
console.log(i+ ' ' + typeof(ob[i]));
if (!ob.hasOwnProperty(i)) {
continue;
}
//Exclude arrays from the final result
//Check this http://stackoverflow.com/questions/4775722/check-if-object-is-array
if(ob[i] && Array === ob[i].constructor){
continue;
}
if ((typeof ob[i]) === 'object') {
flatObject = flattenObject(ob[i]);
for (let x in flatObject) {
if (!flatObject.hasOwnProperty(x)) {
continue;
}
//Exclude arrays from the final result
if(flatObject[x] && Array === flatObject.constructor){
continue;
}
toReturn[i + (!!isNaN(x) ? '.' + x : '')] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
}
@abeMedia

This comment has been minimized.

Copy link

@abeMedia abeMedia commented Sep 27, 2019

Stripping out arrays means this is useless for any data containing them. Would be much better to instead flatten them too e.g.

{ a: ["b", "c"] } => { "a.0": "b", "a.1": "c" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment