Reputation: 361
Here is my code:
var foo = {
age:20
}
console.dir(`hello:${foo}`)
I expect
hello:{ age: 201 }
but I got
'hello:[object Object]'
and if I don't want use
console.log("hello")
console.dir(foo)
is there any way to print "hello" and object's content in one console function?
Upvotes: 2
Views: 1067
Reputation: 44135
Just use JSON.stringify
. What's happening is that when you use the string interpolation ${}
, the toString
method is called - on an object, the result of this is [object Object]
:
console.log({}.toString());
JSON.stringify
converts an object or array to a string, but keeps the content and avoids the toString
output. So just use it like so:
var foo = {
age: 20
};
console.dir(`hello:${JSON.stringify(foo)}`)
Also note that dir
is used for showing the different properties of objects. It's better to just use console.log
, which means you can avoid JSON.stringify
altogether:
var foo = {
age: 20
};
console.log("hello:", foo);
Upvotes: 3
Reputation: 138457
.dir
expects an object to be passed, and shows that as a table. .log
is for logging anything (including strings). Therefore if you want to log a string and an object as a table, you require two different funtionalities, or in other words: two different functions.
If you do that once, there is no sense in writing a 3 line function to reduce two lines into one (well four actually). If you however plan to do that more often, well then ...
Object.defineProperty(console, "taggedDir", {
value(name, table) {
this.log(name);
this.dir(table);
}
});
console.taggedDir("Table:", { /*...*/ });
Upvotes: 0