Created
February 7, 2018 19:15
-
-
Save paitonic/5d575b62560e3c7579639d0f396c3fba to your computer and use it in GitHub Desktop.
flattenObject
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
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