Created
May 17, 2024 12:23
-
-
Save carefree-ladka/5b4a25b227d658a8ada63a5ff8bba2b1 to your computer and use it in GitHub Desktop.
Object flatten in JS
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 getAllKeys = (obj) => { | |
| const result = []; | |
| const queue = [{ path: [], obj }]; | |
| while (queue.length) { | |
| const { path, obj: currentObj } = queue.shift(); | |
| for (const [key, value] of Object.entries(currentObj)) { | |
| const newPath = path.concat(key); | |
| if (typeof value === 'object' && value !== null) { | |
| queue.push({ path: newPath, obj: value }); | |
| } | |
| result.push(newPath.join('.')); | |
| } | |
| } | |
| console.log(result); | |
| return result; | |
| } | |
| const obj = { | |
| a: 1, | |
| b: { | |
| c: 4, | |
| d: { | |
| e: 6, | |
| f: { | |
| g: 10 | |
| } | |
| } | |
| } | |
| }; | |
| getAllKeys(obj); | |
| //[ 'a', 'b', 'b.c', 'b.d', 'b.d.e', 'b.d.f', 'b.d.f.g' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment