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:
If you can use lodash you can do it this way:
> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'
With lodash map()
you can iterate over Objects as well.
This maps every key/value entry to its string representation:
> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]
And join()
put the array entries together.
If you can use ES6 Template String, this works also:
> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'
Please note this do not goes recursive through the Object:
> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]
Like node's util.inspect() will do:
> util.inspect(o)
'{ a: 1, b: { c: 2 } }'