Skip to content

Instantly share code, notes, and snippets.

@DonAmit197
Created June 4, 2023 12:37
Show Gist options
  • Select an option

  • Save DonAmit197/0aebd24fba12e2d48c121b1d9b5ad5f9 to your computer and use it in GitHub Desktop.

Select an option

Save DonAmit197/0aebd24fba12e2d48c121b1d9b5ad5f9 to your computer and use it in GitHub Desktop.
Flatten JSON
/*******
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