Skip to content Skip to sidebar Skip to footer

Can I Print Object As String Like Date In Console.log?

When I create the new Date object and using console.log shows not object but time as string. However, MyObject is print as Object. Example: const date = new Date(); console.log(dat

Solution 1:

I don't think console.log provides any mechanism to tell it what representation to use for the object.

You can do console.log(String(new MyObject())); and give MyObject.prototype a toString method:

constMyObject = function() {
  this.name = 'Stackoverflow';
  this.desc = 'is Good';
};
MyObject.prototype.toString = function() {
    returnthis.name + this.desc;
};

As you're using ES2015+ features (I see that from const), you might also consider class syntax:

classMyObject{
  constructor() {
    this.name = 'Stackoverflow';
    this.desc = 'is Good';
  }
  toString() {
    returnthis.name + this.desc;
  }
}

Solution 2:

tips: in javascript ,you still can use "override" a method to impletement it

demo:

let myobj={id:1,name:'hello'};

Object.prototype.toString=function(){ 

   returnthis.id+' and '+this.name

}; //override toString of 'Global' Object.console.log(obj.toString());// print: 1 is hello

Solution 3:

Actually very simple:

let oldLog = console.log;
console.log = function ()
{
    for (let i = 0; i < arguments.length; i++)
        if (arguments[i] && arguments[i].toString)
            arguments[i] = arguments[i].toString();
    oldLog.apply(null, arguments);
}

Your object should bring a toString method. Might use other criteria than toString to decide what and how to stringify.

Post a Comment for "Can I Print Object As String Like Date In Console.log?"