Thursday, July 15, 2010

cloning json, arrays and stuff...

A few weeks ago i had to handle this really big object (in JS, i'm not gay). I remembered the joke:

-Mommy, mommy the kids won't let me implement a swap function in javascript
-That's because it's impossible, the javascript language passes arguments by value, not reference. You dumbass.

Ok, that joke doesn't exist, is not even funny. The point is that sometimes you may have a json object or an array that you just wanna pass around without further complications. You may also have a json object with arrays inside, etc.

var person = {personality: "moron", age: 23, name: "Cristian"}
var cristian = person;
person.name = "Cris";

Voila! I changed the name of cristian. So far you may know this, and if you don't know it then you might not be such a sniper with JS. There's a solution for this problem, is simple, clone the object, cool. The only problem is that there are no classes in JS, there is an object representation which is as flexible as melted rubber band. So, we CAN do cloning for what it may be a representation of a class, this is a pain in the ass. You may have to implement a method for every object you have, where all you do is copy the properties to another object, and its structure.

I can't imagine looping through each object over and over again. Arrays in arrays, objects in arrays, etc.

Being JS so flexible, we should be capable of implementing a generic cloning function. Being this the case, and being myself such a lazy bastard, i came up with this solution.

function cloneObj(stuff){
            if(stuff == null || typeof(stuff) != 'object'){
                return stuff;
            }
            var temp = new stuff.constructor();
            for(var key in stuff){
                temp[key] = cloneObj(stuff[key]);
            }
            return temp;
        }

Simple method, how does it work? i loop through all the elements, and if the element is an object I do the same for its inner elements. In the end I get a brand new object.

Is this the best solution ever? no, it would ve even cooler to make it a general method, but being as freaking flexible as it is cloneObj can clone any objectish-arraysh-tree-like structure, for real.

Also, the recursive stack in JS is kinda small, so you may get a "too much recursion" error when cloning something big (i mean BIG). It would be cool to make some dynamic programming so this won't happen and make the method lighter.

So, there you go. A little snippet that may save your life if you ever find yourself in a swordfish movie like situation

No comments:

Post a Comment