Jim Jin
Jim Jin

Reputation: 1519

ES6 template literal with object

I have a function which prints an template literal:

function func() {
  const obj = {
    a: 1,
    b: 2
  };
  console.log(`obj = ${obj}`);
}

It prints "obj = [object Object]".

If I want to log the content of the object(prints "obj = {a: 1, b: 2}"), how can I revise the code?

Upvotes: 3

Views: 1720

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

JSON stringify it.

function func() {
  const obj = {
    a: 1,
    b: 2
  };
  console.log(`obj = ${JSON.stringify(obj)}`);
}

func();

Upvotes: 4

Related Questions