Last active
April 26, 2024 14:12
-
-
Save ChecksumFailed/9742dae1855c2e6b8a5eda4d84134d5f 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
/** | |
* Takes a nested object and flattens its to one level. Function recursively calls itself until finished. | |
* //https://stackoverflow.com/questions/34513964/how-to-convert-this-nested-object-into-a-flat-object | |
* @public | |
* @param {Object} currentNode - Current node in the nested object to process | |
* @param {object} flattenedObject - The new object containing the flattened values | |
* @param {object} flattendKey - The current flattened key name. Example: key.key1.key2 | |
* @returns {Object} | |
* @example var testObj = { | |
"key1" : "test1", | |
"key2": "test2", | |
"key3": { | |
"subKey1": true, | |
"subKey2": false, | |
}, | |
"key4": [ | |
"a","b","c" | |
] | |
} | |
flattenObj(testObj); | |
Output: "{ | |
"key1": "test1", | |
"key2": "test2", | |
"key3.subKey1": true, | |
"key3.subKey2": false, | |
"key4.0": "a", | |
"key4.1": "b", | |
"key4.2": "c" | |
} | |
*/ | |
function flattenObj(currentNode, flattenedObject, flattenedKey) { | |
flattenedObject = flattenedObject || {}; | |
for (var key in currentNode) { | |
if (currentNode.hasOwnProperty(key)) { | |
var newKey; | |
if (flattenedKey === undefined) { | |
newKey = key; | |
} else { | |
newKey = flattenedKey + '.' + key; | |
} | |
var value = currentNode[key]; | |
if (typeof value === "object") { | |
flattenObj(value, flattenedObject, newKey); | |
} else { | |
flattenedObject[newKey] = value; | |
} | |
} | |
} | |
return flattenedObject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment