0

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

Ankit Kumar
  • 97
  • 2
  • 9
  • console.log(JSON.stringify(star)) – Eric Nov 09 '21 at 13:12
  • Does this answer your question? [Converting an object to a string](https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string) – Ivar Nov 09 '21 at 13:12

3 Answers3

0

You can use JSON.stringify

console.log(`${JSON.stringify(test)}`)
Eugene
  • 88
  • 1
  • 6
0

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}`);

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.

adiga
  • 34,372
  • 9
  • 61
  • 83
-1

Hey do this simple trick:

console.log({star});

Output:

[Log] {star: {id: 1, name: "Arcturus", visualMag: -0.05}}
Mayank Sharma
  • 844
  • 7
  • 21