Shortcut for adding nested properties to a JavaScript object

JavaScript (intermediate level) posted on 12th Oct 2017

When working on Sheets API - Developer Metadata it becomes clear that some of the request objects can go to quite a depth, so you end up doing something like this.

var r = {a:{b:{c:{d:{e:true}}}};

This becomes more complicated when say,  a.b.c already exists, and has already some other stuff in it. One way round this is to use an extend type function - there is one available in my cUseful.Utils library so you could do this to merge the new data into the old object.

var r = cUseful.Utils.vanExtend ( r ,  a:{b:{c:{d:{e:true}}}} );

But -  you still have to construct that complex object. 

Here's an alternative way - You can get this in the cUseful library (1EbLSESpiGkI3PYmJqWh3-rmLkYKAtCNPi1L2YCtMgo2Ut8xMThfJ41Ex) or on github

Propify

The idea is to be able to specify the parent properties you need in the resulting object as a string
var r = propify ( "a.b.c.d", r); 

will create an object of the required structure, so you can just do this. Any existing objects in the heirarchy will be preserved, and any missing ones will be added
 r.a.b.c.d.e = true;

or even this
 propify ( "a.b.c.d", r).e=true; 

Here's some examples and results
function testPropify() {

  // get from library
  var propify = cUseful.Utils.propify;
  
  Logger.log (propify("details")); // {details={}}
  Logger.log (propify("details.profile")); //{details={profile={}}}
  
  var card = propify("contact.details.profile", {contact:{}}); 
  Logger.log (card);    // {contact={details={profile={}}}}
  
  propify ("contact.details.profile.telephones", card);
  Logger.log (card);    // {contact={details={profile={telephones={}}}}}
  
  // can use a branch of the object to propify it, and will return the branch
  var profile = propify ("telephones", card.contact.details.profile); 
  Logger.log (card);    // {contact={details={profile={telephones={}}}}}
  Logger.log (profile); // {telephones={}}
  
  // add another couple of branches 
  propify ("emails" , profile);
  propify ("urls", card.contact.details);
  
  Logger.log (card);   // {contact={details={urls={}, profile={emails={}, telephones={}}}}}
  
  // we can use the branch
  profile.telephones.mobile="1234"
  
  // or the full object
  card.contact.details.profile.telephones.home="1234";
  
  Logger.log (card); // {contact={details={urls={}, profile={emails={}, telephones={mobile=1234, home=1234}}}}}
  
  // should fail because mobile is not an object
  propify ("contact.details.profile.telephones.mobile", card);
  
}
 

The code

Propify code is the library, but also below for convenience. There's not much to it, but it's pretty handy.

/**
   * a short cut to add nested properties to a an object
   * @param {object} [base] the base object
   * @param {string} propertyScheme something like "a.b.c" will extend as necessary
   * @return {object} base updated
   */
   ns.propify = function (propertyScheme ,base) {
    
    // if base not specified, create it
    if (typeof base === typeof undefined) base = {};
    
    // make sure its an object
    if (typeof base !== typeof {} ) throw 'propify:base needs to be an object';
    
    // work through the scheme
    (propertyScheme || "").split (".")
      .reduce (function (p,c) {
      
        // add a branch if not already existing
        if (typeof p[c] === typeof undefined) p[c] = {};
        
        // make sure we're not overwriting anything
        if (typeof p[c] !== typeof {}) throw 'propify:branch ' + c + ' not an object in ' + propertyScheme;
        
        // move down the branch
        return p[c];
  
      } , base);
    
    // now should have the required shape
    return base;
  
  };

For more like this, see Google Apps Scripts snippets. Why not join our community , follow the blog, twitter, G+ .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