Skip to content

Instantly share code, notes, and snippets.

@paitonic
Created February 7, 2018 19:15
Show Gist options
  • Save paitonic/5d575b62560e3c7579639d0f396c3fba to your computer and use it in GitHub Desktop.
Save paitonic/5d575b62560e3c7579639d0f396c3fba to your computer and use it in GitHub Desktop.
flattenObject
function isObject(value) {
return (value && value.constructor && value.constructor === Object) === true;
}
function isArray(value) {
return value instanceof Array;
}
function isPrimitive(value) {
return !isObject(value) && !isArray(value);
}
function flattenObject(object) {
var flattened = {};
function _flatten(object, path) {
if (isObject(object)) {
var keys = Object.keys(object);
while (next = keys.pop()) {
path.push('[\'' + next + '\']');
_flatten(object[next], path);
path.pop();
}
} else if (isArray(object)) {
for (var i = 0, max = object.length; i < max; i += 1) {
path.push('[' + i + ']');
_flatten(object[i], path);
path.pop();
}
} else if (isPrimitive(object)) {
flattened[path.join('')] = object;
}
}
_flatten(object, []);
return flattened;
}
flattenObject(object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment