Home > Software engineering >  Javascript How to print an object using string interpolation
Javascript How to print an object using string interpolation

Time:11-10

is there any way to print the object using string interpolation method?

const star = {
    id: 1,
    name: 'Arcturus',
    visualMag: -0.05,
};

This method doesnt work

console.log(`${star}`); // [object Object]

This works

console.log(`${star.name}`); // 'Arcturus'

and simply using console.log(star) works

CodePudding user response:

Hey do this simple trick:

console.log({star});

Output:

[Log] {star: {id: 1, name: "Arcturus", visualMag: -0.05}}

CodePudding user response:

You can use JSON.stringify

console.log(`${JSON.stringify(test)}`)

CodePudding user response:

When you use an object within template literal, it coerces the object to a string. It looks for a toString method on the object. If it is not found, it will use Object.prototype.toString method which returns "[object Object]".

So, add a toString property to the object.

const star = {
  id: 1,
  name: 'Arcturus',
  visualMag: -0.05,
};

Object.defineProperty(star, "toString", {
  value: function() {
    return JSON.stringify(this)
  }
})

console.log(`${star}`);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note: You could directly add star.toString = function() { ... }. But, that will add an enumerable property to the object and will be displayed when you log the object directly.

  • Related