Created
June 4, 2023 12:37
-
-
Save DonAmit197/0aebd24fba12e2d48c121b1d9b5ad5f9 to your computer and use it in GitHub Desktop.
Flatten JSON
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
| /******* | |
| The purpose of this function is to flatten the Nested or tree structure JSON data | |
| ******/ | |
| var flatten = (function (isArray, wrapped) { | |
| return function (table) { | |
| return reduce("", {}, table); | |
| }; | |
| function reduce(path, accumulator, table) { | |
| if (isArray(table)) { | |
| var length = table.length; | |
| if (length) { | |
| var index = 0; | |
| while (index < length) { | |
| var property = path + "[" + index + "]", item = table[index++]; | |
| if (wrapped(item) !== item) accumulator[property] = item; | |
| else reduce(property, accumulator, item); | |
| } | |
| } else accumulator[path] = table; | |
| } else { | |
| var empty = true; | |
| if (path) { | |
| for (var property in table) { | |
| var item = table[property], property = path + "." + property, empty = false; | |
| if (wrapped(item) !== item) accumulator[property] = item; | |
| else reduce(property, accumulator, item); | |
| } | |
| } else { | |
| for (var property in table) { | |
| var item = table[property], empty = false; | |
| if (wrapped(item) !== item) accumulator[property] = item; | |
| else reduce(property, accumulator, item); | |
| } | |
| } | |
| if (empty) accumulator[path] = table; | |
| } | |
| return accumulator; | |
| } | |
| }(Array.isArray, Object)); | |
| //static-content-hash-trigger-GCC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment