Search code examples
ecmascript-6template-literals

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?


Solution

  • JSON stringify it.

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