views:

145

answers:

3

I think JavaScript doesn't have anything like obj.first, but I was wondering if something like this can be achieved in any way:

var foobar = { aint: "foo", an: "bar", array: "foobar" };
var recursiveObjDump = function (obj, idx) {
    if (idx == obj.last.index) return obj[idx];
    else return obj[idx] + " " + recursiveObjDump(obj, obj[idx].next.index);
};

alert( recursiveObjDump(foobar, foobar.first.index) );

Thanks.

A: 

You can use for in to loop through all the properties.

This is a basic one, you could add better detection to look for Arrays and such as well.

var foobar = { aint: "foo", an: "bar", array: "foobar" };

function recusiveDump(obj) {
    var output = '';
    for(var i in obj) {
     if(obj.hasOwnProperty(i)) {
      if(typeof obj[i] == 'object') {
       output += recusiveDump(obj[i]);
      } else {
       output += obj[i];
      }
     }
    }
    return output;
}

alert(recusiveDump(foobar));
seanmonstar
Thanks for the answer, but the 'for' construct is precisely what I'm trying to avoid. That recursive dump isn't very recursive, is it?
R.
The function `recursiveDump` calls itself; therefore it is recursive.
Matt Ball
+1  A: 

Not really. Objects in Javascript are associative arrays - sets of key/value pairs. There is no specified order, just as in a mathematical set (compare to a sequence). Therefore, looking for something like object.first is meaningless.

On the other hand, you can absolutely impose your own structure on top of this. For instance, you could implement Lisp-style lists in Javascript, and recur over those. This is a pretty neat article on using functional programming techniques in Javascript.

In the end, Javascript is object-oriented, not functional, so you're just not going to find those functional primitives implemented natively.

Edit: If you still want to use functional programming techniques in Javascript, have a look at Functional Javascript.

Matt Ball
A: 

If you just want to serialize an object, use JSON.stringify(). It is native in Javascript 5, and you can download a script from Crockford's site for lower javascript versions. (the same script can reparse the JSON object serialization safely back to a javascript object again)

Roland Bouman