Traversing/Navigating Objects in Javascript

Once in a while, you learn something and go years before encountering the same scenario again. By that time you’ve probably forgotten all about it’s idiosyncrasy. Well…

I just spent 2 hours messing around with Javascript Objects. You see early on, I adopted a strict use of dot syntax. It jived with me so that’s what I used. I would use javascript arrays as well, but in my mind the two were mutually exclusive…not true. It turns out, if you can’t use dot syntax (let’s say you’re using dynamic variables to traverse an object instead of looping through every single property) then you can use an array syntax. Yes, that’s frickin correct…on object literals, you can treat them like arrays.

Now I actually knew this at one point, but forgot it years ago because I have a process for things and somehow that process has precluded me from encountering dynamically generated object traversals.

Anyway, fuck, here it is:

 

var obj = {
    thing: 1,
    things: "some more shit",
    thingz: {
        stuff: 2,
        stuffz: 'awh man!'
    }
}

console.debug(obj.thingz.stuffz);

 

So we’re all used to that, but it turns out, this works as well:

 

var obj = {
                    thing: 1,
                    things: "some more shit",
                    thingz: {
                        stuff: 2,
                        stuffz: 'awh man!'
                    }
                }

                console.debug(obj.thingz.stuffz);

                var t = "thingz";
                var s = "stuffz";

                console.debug(obj[t][s]);

 

Crazy shit right? Well not really, but sometimes its good to remember the small stuff… It can save you from say, having to traverse an entire object with an “if” statement looking for a string.

Anyway…

Leave a Reply

Your email address will not be published. Required fields are marked *