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:
Take a look at the jQuery-JSON plugin
At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.
I was looking for this, and wrote a deep recursive one with indentation :
function objToString(obj, ndeep) {
if(obj == null){ return String(obj); }
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return '{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray];
default: return obj.toString();
}
}
Usage : objToString({ a: 1, b: { c: "test" } })
As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj)
:
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
I hope this example will help for all those who all are working on array of objects
var data_array = [{
"id": "0",
"store": "ABC"
},{
"id":"1",
"store":"XYZ"
}];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
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);
It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});