Converting an object to a string
I would recommend using JSON.stringify
, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Use javascript String() function
String(yourobject); //returns [object Object]
or stringify()
JSON.stringify(yourobject)
Sure, to convert an object into a string, you either have to use your own method, such as:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604
or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you 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.
Update:
A more modern solution would be:
function objToString (obj) {
let str = '';
for (const [p, val] of Object.entries(obj)) {
str += `${p}::${val}\n`;
}
return str;
}
or:
function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
Keeping it simple with console
, you 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); // :)
Output:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());