Skip to content

Instantly share code, notes, and snippets.

@harish2704
Created January 18, 2017 05:59
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 harish2704/93df7df179c37dbb6888f9c073ae1e1d to your computer and use it in GitHub Desktop.
Save harish2704/93df7df179c37dbb6888f9c073ae1e1d to your computer and use it in GitHub Desktop.
Flatten a nested json into a plain json
var handlers = {
Object: flattenObject,
Array: flattenArray,
};
function router(val, store, prefix, i ) {
var kind, handler, key = prefix? prefix + '.'+ i : i; ;
if( val === undefined || val === null ){
return store[ key ] = val;
}
kind = val.constructor.name;
handler = handlers[kind];
if (handler) {
return handler(val, store, key);
}
return store[ key ] = val;
}
function flattenObject(obj, store, prefix) {
var i, val, kind, handler;
for (i in obj) {
router( obj[i], store, prefix, i );
}
}
function flattenArray(obj, store, prefix) {
var i=0, l = arr.length;
while (i < l) {
router( arr[i], store, prefix, i );
i++;
}
}
function flatten( obj ){
var out = {};
flattenObject( obj, out, '' );
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment