Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cvan
Created April 16, 2020 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvan/00f482311fedbab0c560c8fc1e676e1e to your computer and use it in GitHub Desktop.
Save cvan/00f482311fedbab0c560c8fc1e676e1e to your computer and use it in GitHub Desktop.
flatten a nested JavaScript object to a flatten one-level object
// Adapted from source: https://stackoverflow.com/a/19204980
const flatten = (function(isArray, wrapped) {
return function(table) {
return reduce('', {}, table);
};
function reduce(path, accumulator, table) {
if (isArray(table)) {
const length = table.length;
if (length) {
let index = 0;
while (index < length) {
const property = path + '[' + index + ']';
const item = table[index++];
if (wrapped(item) === item) {
reduce(property, accumulator, item);
} else {
accumulator[property] = item;
}
}
} else accumulator[path] = table;
} else {
let empty = true;
let item;
let property;
if (path) {
for (property in table) {
item = table[property];
property = path + '.' + property;
empty = false;
if (wrapped(item) === item) {
reduce(property, accumulator, item);
} else {
accumulator[property] = item;
}
}
} else {
for (property in table) {
item = table[property];
empty = false;
if (wrapped(item) === item) {
reduce(property, accumulator, item);
} else {
accumulator[property] = item;
}
}
}
if (empty) {
accumulator[path] = table;
}
}
return accumulator;
}
})(Array.isArray, Object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment