Reputation: 1481
If I create an object and use console.log it will expand the object and I can see the object properties. If I use alert it does not. Is there any way to do the same thing in an alert?
car=new Object();
car.wheels=4;
car.make="honda";
car.owner="me"
console.log(car);
output: Object { wheels: 4, make: "honda", owner: "me" }
alert(car)
output is [object Object]
How can I get the same output for the alert?
Upvotes: 1
Views: 2280
Reputation: 10945
As others have stated you use JSON.stringify
.
But I wanted to give a few other pointers. I don't know if you know these already, but your example indicated that you might appreciate the tips.
new Object()
Instead just create your object:var car = {
wheels: 4,
make: "honda",
owner: "me"
}
Always use var
, let
or const
when creating variables. If you don't then they are created on the global scope. In the browser you would be creating the new variables on the window
object.
JSON.stringify
has other parameters:
JSON.stringify(value[, replacer[, space]])
The replacer
is not often used, but it can provide a way of filtering and preventing recursive data.
The space
parameter can be a number form 0 to 10 or a number of characters in a string from 0 to 10. This indicates how much to indent each level in the output.
function replacer(key, value) {
if (typeof value === 'string') {
return undefined;
}
return value;
}
var foo = {
company: 'Sony',
model: 'Playstation',
version: 4,
pricing: [
{
pro: false,
price: 299.00
},
{
pro: true,
price: 399.00
}
],
comments: 'none'
};
alert(JSON.stringify(foo, replacer, 2));
alert(JSON.stringify(foo, replacer, '----'));
Upvotes: 4
Reputation: 119
In the console log method, the parameter is considered as an object. So, the object can be in any form like an array, string, integer, etc., and We will get the content. But in the alert method, it accepts only the string. So, if you send the object, it will convert it as string version of the object ( object Object ). If you stringify the object and send as a parameter to the alert method, it will display the content. Try this one,
window.alert(JSON.stringify(object));
Upvotes: 1