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 :(
Use javascript String() function.
or
.
JSON methods are quite inferior to the Gecko engine .toSource() primitive.
See the SO article response for comparison tests.
Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).
(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)
which displays:
and
and
stringify-object
is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-objectthen:
Obviously it's interesting only if you have circular object that would fail with
JSON.stringify();
If you can use lodash you can do it this way:
With lodash
map()
you can iterate over Objects as well. This maps every key/value entry to its string representation:And
join()
put the array entries together.If you can use ES6 Template String, this works also:
Please note this do not goes recursive through the Object:
Like node's
util.inspect()
will do:As firefox does not stringify some object as screen object ; if you want to have the same result such as :
JSON.stringify(obj)
:I hope this example will help for all those who all are working on array of objects