Last active
March 6, 2021 18:36
-
-
Save kraftdorian/dfab0d2daaa5f160e776cd37ce83cc7c to your computer and use it in GitHub Desktop.
Flatten object with paths
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
const flattenObject = (value, key = null, flattenedObject = {}) => { | |
if ( | |
['string', 'number', 'bigint', 'boolean', 'undefined', 'symbol'].includes(typeof value) || | |
value === null || | |
value instanceof Date | |
) { | |
flattenedObject[key] = value; | |
} else if (Array.isArray(value)) { | |
value.forEach((childValue, childIndex) => { | |
flattenObject(childValue, `${key}[${childIndex}]`, flattenedObject); | |
}); | |
} else if (typeof value === 'object') { | |
let computedKey; | |
for (const childKey in value) { | |
computedKey = (typeof key === 'string' ? key + '.' : '') + childKey; | |
flattenObject(value[childKey], computedKey, flattenedObject); | |
} | |
} | |
return flattenedObject; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case:
Result: