Reputation: 29
console.log(({
title: "The Three Musketeers",
author: "Alexandre Dumas",
price: "$49"
}).toString());
It outputs an Object as [object Object]
, even though I am calling .toString() on it. Can anyone please explain why this happens?
Upvotes: 1
Views: 576
Reputation: 40
The method you're looking for is JSON.stringify(). Try this:
JSON.stringify({
title: "The Three Musketeers",
author: "Alexandre Dumas",
price: "$49"
}, null, 2);
Upvotes: 0
Reputation: 7777
If you do it this way it will work better
let object = {
title: "The Three Musketeers",
author: "Alexandre Dumas",
price: "$49"
}
console.log("My object",object);
It's because it doesn't know how to render your object
Upvotes: 0
Reputation: 22766
That's what happens when you try to convert or add an object to a string (which also tries to convert it to a string), what you're looking for is JSON.stringify(object)
:
console.log(
JSON.stringify(
{title : "The Three Musketeers", author: "Alexandre Dumas", price: "$49"}
)
);
Upvotes: 1
Reputation: 16576
If you're looking for a JSON string representation of the object, look into JSON.stringify()
Upvotes: 0
Reputation: 42304
Because for have built a JavaScript object that you are attempt to convert to a string. You are attempting to convert the entire object to a string, which can't (really) be done. As such, you simply get text that says "Hey, we've got an object here".
If however, you were to run .toString()
on a property of that object (which is probably your intent), you would get a string representation of that property. This can be done by accessing the proeprty with the dot notation just before calling .toString()
, as follows:
console.log(({
title: "The Three Musketeers",
author: "Alexandre Dumas",
price: "$49"
}).title.toString());
Upvotes: 1