Sometimes you need to blow out a JavaScript object so that the keys are fully qualified. For example, if you are doing a rest query on some third party database, or to represent a more than 1 level deep object in a two dimension space like a spreadsheet.
Page Content
hide
The problem
Your object looks like this
{a:1,b:2,c:{d:3,e:{f:25}}}
but you need it to look like this
{a:1,b:2,"c.d":3,"c.e.f":25}
The code
First – we need to flatten it, so we get this
[{key:[a], value:1},{key:[b], value:2} , {key:[c,d], value:3}, {key:[c,e,f], value:25}]
function objectSplitKeys (ob,obArray,keyArray) { obArray = obArray || []; //turns this {a:1,b:2,c:{d:3,e:{f:25}}} // into this, so that the keys can be joined to make dot syntax //[{key:[a], value:1},{key:[b], value:2} , {key:[c,d], value:3}, {key:[c,e,f], value:25}] if (isObject(ob)) { Object.keys(ob).forEach ( function (k) { var ka = keyArray ? keyArray.slice(0) : []; ka.push(k); if(isObject(ob[k])) { objectSplitKeys (ob[k],obArray,ka); } else { obArray.push ( {key:ka, value:ob[k]} ); } }); } else { obArray.push(ob); } return obArray; } function isObject (obj) { return obj === Object(obj); }
and we also need to join the resultant keys with dots.
function objectDot(ob) { return objectSplitKeys (ob).map ( function (o) { return {key:o.key.join("."), value:o.value}; }); }
and finally, put it all together to make a new object with the flattened keys
var dotJob = objectDot (ob).reduce(function(p,c){ p[c.key] = c.value; return p; },{});
See Database abstraction and Google Apps Script, Database abstraction with google apps script and Google Apps Scripts snippets for more like this