javascript tutorial - [Solved-5 Solutions] Converting an object to a string - javascript - java script - javascript array



Problem:

How can We convert a JavaScript object into a string?

Solution 1:

Example:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
click below button to copy the code. By JavaScript tutorial team

Output

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

Solution 2:

Sure, to convert an object into a string, we either have to use our own method, such as:

function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}
click below button to copy the code. By JavaScript tutorial team

Actually, the above just shows the general approach; we may wish to use something like or, if we are not using methods (functions as properties of our object), we may be able to use the new standard (but not implemented in older browsers, though we can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON

Solution 3:

Use javascript String() function. String(yourobject); OR JSON.stringify(yourobject)

Solution 4:

Keeping it simple with console, we can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console. Example:

var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o);   // :)
click below button to copy the code. By JavaScript tutorial team

Output

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)

Solution 5:

EDIT Do not use this answer as it does not work in Internet Explorer. Use Gary Chambers solution. toSource() is the function we are looking for which will write it out as JSON.

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Converting an object to a string