Last active
October 3, 2018 00:19
-
-
Save lmcardle/f12fe73334b76d4ec9ee7697ffb5e5fe to your computer and use it in GitHub Desktop.
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
function flattenObject(objToFlatten) { | |
let result = {}; | |
let objectsToFlatten = [objToFlatten]; | |
while (objectsToFlatten.length) { | |
let currentObject = objectsToFlatten.pop(); | |
let currentKeys = Object.keys(currentObject); | |
for (let i=0; i<currentKeys.length; i++) { | |
let currentKey = currentKeys[i]; | |
let currentItem = currentObject[currentKey]; | |
if (typeof(currentItem) === 'object') { | |
let childKeys = Object.keys(currentItem); | |
let newChildObject = {}; | |
childKeys.forEach((key) => { | |
newChildObject[`${currentKey}.${key}`] = currentItem[key]; | |
}); | |
objectsToFlatten.push(newChildObject); | |
} else { | |
result[currentKey] = currentItem; | |
} | |
} | |
} | |
return result; | |
} | |
let myObject = { | |
a: 5, | |
b: 6, | |
c: { | |
f: 9, | |
g: { | |
m: 17, | |
n: 3 | |
} | |
} | |
} | |
console.log(flattenObject(myObject)) // should produce {a: 5, b: 6, c.f: 9, c.g.m: 17, c.g.n: 3} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment