How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
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:
Output:
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
If you want a minimalist method of converting a variable to a string for an inline expression type situation,
''+variablename
is the best I have golfed.If 'variablename' is an object and you use the empty string concatenation operation, it will give the annoying
[object Object]
, in which case you probably want Gary C.'s enormously upvotedJSON.stringify
answer to the posted question, which you can read about on Mozilla's Developer Network at the link in that answer at the top.One option:
console.log('Item: ' + JSON.stringify(o));
Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:
console.log('Item: ', o);
If you're just outputting to the console, you can use
console.log('string:', obj)
. Notice the comma.In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.
For example the following would convert all items in "value" to a string:
More details here:
http://www.w3schools.com/jsref/jsref_string.asp
For your example, I think
console.log("Item:",o)
would be easiest. But,console.log("Item:" + o.toString)
would also work.Using method number one uses a nice dropdown in the console, so a long object would work nicely.