javascript tutorial - [5 Solutions] Display a JavaScript object - javascript - java script - javascript array
Problem:
How can we display a JavaScript object?
Solution 1:
If we want to print the object for debugging purposes, we suggest instead installing Firebug for Firefox and using the code: console.log(obj)
Solution 2:
Use native JSON.stringify
method. Works with nested objects and all major browsers support this method.
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
click below button to copy the code. By JavaScript tutorial team
Solution 3:
If we want to use alert, to print your object, we can do this:
alert("myObject is " + myObject.toSource());
click below button to copy the code. By JavaScript tutorial team
It should print each property and its corresponding value in string format.
Solution 4:
Function:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
click below button to copy the code. By JavaScript tutorial team
Usage:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson@hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
click below button to copy the code. By JavaScript tutorial team
Solution 5:
var getPrintObject=function(object)
{
return JSON.stringify(object);
}