Last active
August 29, 2015 14:01
-
-
Save shimondoodkin/18944ba65339a871f8cf to your computer and use it in GitHub Desktop.
serialization of hierarchical object/array/int/str to a flat object and back
This file contains 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
// serialization of hierarchical object/array/int/str to a flat object and back | |
// | |
// useful to store an object in compressed column store | |
// so it will be compressed by type and not as blob. | |
// the resulting object values and keys can be escaped and converted to a sql query | |
//example: | |
// var xx=['test',{data:[1,2,"asd"]}] | |
// result=flat(xx) | |
// | |
// result: | |
// { | |
// a0:'test', | |
// a1_odata_a0:1, | |
// a1_odata_a1:2, | |
// a1_odata_a2:'asd' | |
// } | |
function flat(a,pf,ret) | |
{ | |
if(pf===undefined)pf=''; | |
if(ret===undefined)ret={}; | |
var pp=a instanceof Array?'a':'o'; | |
Object.keys(a).forEach(function(k) | |
{ | |
var v=a[k]; | |
if(v instanceof Object) | |
return flat(v,pf+pp+k+'_',ret) | |
else | |
ret[pf+pp+k]=v; | |
}); | |
return ret; | |
} | |
exports.flat=flat; | |
//example: | |
// var fxx= | |
// { | |
// a0:'test', | |
// a1_odata_a0:1, | |
// a1_odata_a1:2, | |
// a1_odata_a2:'asd' | |
// } | |
// result=unflat(fxx) | |
// | |
// result: | |
// ['test',{data:[1,2,"asd"]}] | |
function unflat(a) | |
{ | |
var ret={}; | |
Object.keys(a).forEach(function(k) | |
{ | |
var v=a[k] | |
var splitedkey=k.split('_'); | |
var pt=ret; | |
var prevkey='ret'; | |
for(i=0;i<splitedkey.length;i++) | |
{ | |
var prefixedkey=splitedkey[i]; | |
var prevkeytype=prefixedkey[0]; | |
var currentkey=prevkeytype=='o'?prefixedkey.substring(1):parseInt(prefixedkey.substring(1)); | |
if(!(prevkey in pt)) pt[prevkey]=(prevkeytype=='o'?{}:[]); | |
pt=pt[prevkey] | |
prevkey=currentkey; | |
} | |
pt[prevkey]=v; | |
}) | |
return ret.ret; | |
} | |
exports.unflat=unflat; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment