Can’t print objects using template string?

Asked

Viewed 68 times

4

Why doesn’t string template print objects correctly? I have the following test code:

const obj = { a: 1, b: 2, c: 3,}
console.log(`Novo Obj ${obj}`)

and the result on the console comes out as:

Novo Obj [object Object]

do not understand, why if I ask to print without the template, console.log('Novo Obj ', obj) he prints right

Novo Obj  { a: 1, b: 2, c: 3 }

I cannot print objects using the template?

  • You’re probably referring to Visual Studio Code (or just VS Code) and not Visual Code Studio. If so, it is not only for Javascript, it has support for several languages, including Java. The second question is completely different from the first, ask it in another question

2 answers

7


When you do console.log('Novo Obj ', obj), is passing the object as one of the arguments of console.log (the comma separates the arguments, then the string 'Novo Obj' is the first argument, and the object is the second).

That is to say, obj is treated "separately" and printed as per the implementation - that is, it varies according to the environment: testing on Chrome and Node, and the result was { a: 1, b: 2, c: 3 }, in Firefox was Object { a: 1, b: 2, c: 3 }, and in the snippet of the site, the result is:

{
  "a": 1,
  "b": 2,
  "c": 3
}

Turn and see the difference (press F12 and compare the output of snippet below with your console browser):

const obj = { a: 1, b: 2, c: 3 };
console.log(obj);

Note that in the above case, there are quotes around a, b and c, and there are line breaks between them (in the case of Chrome and Firefox, I got the result without the quotes and everything in a single line). The fact is that the result of console.log varies depending on the implementation, but in general, "all" prints the attributes and values of the object.


Already when you put the object inside a string template, internally is called your method toString. But since you didn’t define this method in your object, it uses the inherited method of Object, that always returns something like "[Object type]" - being that type will be the type of the same, which in your case is Object.

So one way to solve it is to define the method toString in its object:

const obj = { a: 1, b: 2, c: 3,
    toString: function() {
        return `a=${this.a}, b=${this.b}, c=${this.c}`;
    }
};
console.log(`Novo Obj ${obj}`); // Novo Obj a=1, b=2, c=3

Of course, if you want, you can use JSON.stringify (which is usually a quick, easy and therefore widely used way for this purpose):

const obj = { a: 1, b: 2, c: 3,
    toString: function() {
        return JSON.stringify(this);
    }
};
console.log(`Novo Obj ${obj}`); // Novo Obj {"a":1,"b":2,"c":3}
// ou use JSON.stringify diretamente
console.log(`Novo Obj ${JSON.stringify(obj)}`); // Novo Obj {"a":1,"b":2,"c":3}


A but with JSON.stringify is when you have circular references:

let a = { x: 1 };
let b = { y: 2, z: a }; // "b" tem referência para "a"
a['z'] = b; // "a" tem referência para "b"

console.log(JSON.stringify(a)); // erro

Then you’d have to use something like that to solve. But then I find it easier to overwrite toString and put the fields you want.

2

Using the literal template works a little different, in this case you need to serialize the object using for example stringify, or access the properties:

const obj = { a: 1, b: 2, c: 3}

console.log(`Novo obj.a ${obj.a}`);

console.log(`Novo obj completo ${JSON.stringify(obj)}`)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.