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
1 |
{a:1,b:2,c:{d:3,e:{f:25}}} |
1 |
{a:1,b:2,"c.d":3,"c.e.f":25} |
The code
First – we need to flatten it, so we get this
1 |
[{key:[a], value:1},{key:[b], value:2} , {key:[c,d], value:3}, {key:[c,e,f], value:25}] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
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); } |
1 2 3 4 5 |
function objectDot(ob) { return objectSplitKeys (ob).map ( function (o) { return {key:o.key.join("."), value:o.value}; }); } |
1 2 3 4 |
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