0

I am trying to generate an object literal string from an object. I know I can myself create a function to do this with something like:

//pseudocode
function getOL(object){
  for(var prop in object){
    if(!object.hasOwnProperty(prop)){return;}
    else if (typeof var === object){/*recur*/}
    //case function
    //case string
  }
}

However, this method seems pretty grossly inefficient. Even if there isn't a native function, which is what seems like is the case, is there some alternative way to write this that is more efficient than recursively looping over every property of an object and its children?

7
  • If this is just for debugging purposes, then I would suggest that you just get Firebug and use console.debug(). Commented Nov 8, 2012 at 18:38
  • 1
    JSON.stringify may work to an extent. It even accepts arguments to control indentation. Commented Nov 8, 2012 at 18:40
  • @Travesty3 That was how I got here in the first place, but turned into me just being annoyed that there wasn't a more efficient way to get that string back out. I wonder how FireBug implements that method, though. Commented Nov 8, 2012 at 18:45
  • @pimvdb interesting. stackoverflow.com/questions/1480393/… seems to imply that JSON.stringify() has some inconsistencies. That said, someone also claims that github.com/douglascrockford/JSON-js is the basis for modern stringifiy methods, so I'll have a look at how they have gone about this. Commented Nov 8, 2012 at 18:50
  • 2
    @MaxPRafferty: What else did you expect? To serialize a [JS object] tree, you will have to iterate its nodes. Commented Nov 8, 2012 at 19:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.