Sunday, January 25, 2015

Difficult to check or initialize javascript object-tree

In javascript I have many times tried to get rid of these scenarios and I think most people don't even end up in these situations. I've ended up in them many many times. The situation is that I have to check if the object-tree exists like so:

function dataManipulator(dataFromOutside) {
   var one = dataFromOutside;

   if(one.two && one.two.three && one.two.three.four && one.two.three.four) {
      one.two.three.four.value = 1;
   }
}

And the same goes especially well with initializations:
   one = one || {};
   one.two = one.two || {};
   one.two.three = one.two.three || {};
   one.two.three.four = one.two.three.four || {};
   one.two.three.four.value = 1;

I ended up in these situations especially when I was using firebase (external database service) and also when I was programming a game, which had objects with big and complex data-structures.

EDIT:
So I finally decided to fix this issue. I have a tendency of thinking things only from one angle for too long, so this was a hard issue for me originally. I finally decided to use eval as I always avoid it, but this really calls for it. So here are object checker and initializer:

http://jsfiddle.net/cuh8yghj/

function objectInitializer(obj, path) {
   var pathSoFar = "obj";

   path.forEach(function(realIndex) {
      pathSoFar += "['" + realIndex + "']";
      if(eval(pathSoFar) === undefined || eval(pathSoFar) === null) {
         eval(pathSoFar + " = {}");
      }
   });
}

function objectChecker(obj, path) {
   var pathSoFar = "obj";

   return path.every(function(realIndex) {
      pathSoFar += "['" + realIndex + "']";
      if(eval(pathSoFar) === undefined || eval(pathSoFar) === null) {
         return false;
      }
       return true;
   });
   
}