1

I am trying to turn an object into a string in vanilla JavaScript for a library toString() function.
The desired output would be something like as follows.

var obj = {a: 1, b:2, c:"string"}
function toString(ins) {
    if(typeof ins === "object" && ins.length === undefined) {
        var str = "";
        //convert to string
        return str;
    }
}
toString(obj)
//should return "a:1, b:2, c:string"

I tried looking here,but couldn't find a suitable answer.

Community
  • 1
  • 1
Travis
  • 1,274
  • 1
  • 16
  • 33
  • 6
    You might want to look at what `JSON.stringify(obj)` does because it handles nested objects and is an industry standard format. It wouldn't be exactly the output you are asking for (quotes in a few different places), but it is built into all modern browsers so you might want to start with that. `JSON.parse(str)` is the reverse process for parsing. – jfriend00 Feb 15 '15 at 00:17

1 Answers1

2

As I said in my comment, it's probably best for you to consider using JSON.stringify(obj) and adapting your code to use that industry standard function even though it doesn't generate the exact output you asked for.

If you really want exactly what you asked for and want to do your own, then you can do this:

var obj = {a: 1, b:2, c:"string"}
function toString(ins) {
    if(typeof ins === "object" && ins.length === undefined) {
        var pieces = [];
        for (var prop in ins) {
            if (ins.hasOwnProperty(prop)) {
                pieces.push(prop + ":" + ins[prop]);
            }
        }
        return pieces.join(", ");
    }
}
toString(obj);

Working demo: http://jsfiddle.net/jfriend00/L70doyu5/

Caveat: This doesn't handle nested objects. You'd want to use a recursive algorithm to handle nested objects.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Or instead of the peices and for loop, `str.replace(/"/g, "")` and `str.replace(/,/g, ", ")`, etc. – Travis Feb 15 '15 at 00:21
  • @Wyatt - I presume you mean do the `JSON.stringify()` first and then `.replace()` the internal quote marks. That is one option, but would have issues with any double quote characters in your actual values. – jfriend00 Feb 15 '15 at 00:24
  • It's probally more complicated than I wrote, but to properly remove only the unwanted double quotes, I'd do something like `str.replace(/{"/g, ""); str.replace(/":/g, ":")` – Travis Feb 15 '15 at 00:27
  • @Wyatt - if you think that's the best answer, feel free to post an answer your own question. I fiddled with the idea a bit and determined that it's not easy to cover all possible things that could be in a string value that you don't want the `.replace()` to impact while getting everythnig else so I probably wouldn't go that direction. – jfriend00 Feb 15 '15 at 00:34
  • I will once I completely finish the algorithm, but for now I'll keep working. Also, a function to get the depth of any object would work for recurring for nested objects. – Travis Feb 15 '15 at 01:08