Flattening an object with dot syntax

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.

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;
         },{});


For help and more information join our forumfollow the blogfollow me on twitter

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.




Comments