Reputation: 1108
I have this code:
const obj = {name: 'maro', age: 77}
console.log(obj); // it logs { name: 'maro', age: 77 }
It seems like evident! but I want to know how console.log internally works ? which methods of "obj" it calls to get the "{ name: 'maro', age: 77 }"
obj contains those properties:
obj.__defineGetter__ obj.__defineSetter__ obj.__lookupGetter__ obj.__lookupSetter__ obj.__proto__ obj.constructor obj.hasOwnProperty
obj.isPrototypeOf obj.propertyIsEnumerable obj.toLocaleString obj.toString obj.valueOf obj.age obj.name
But none of them returns "{ name: 'maro', age: 77 }"!
even obj.toString()
returns '[object Object]'
Upvotes: 3
Views: 203
Reputation: 10356
As you can see in Node.js console.log
documentation, it uses, behind the scenes, util.format
to format its output.
According to util.format
documentation, it returns a string representation of an object with generic JavaScript object formatting, similar to util.inspect
.
You can see its actual implementation, at least for Node.js, here: https://github.com/nodejs/node/blob/75dc8938a40100a53323ed87159a1ab2f149ceca/lib/internal/util/inspect.js#L1567. Have fun reading this code :)
Upvotes: 1
Reputation: 5600
You can use valueOf().
const object1 = {name:"ankit",age:27}
console.log(object1.valueOf());
Note: Objects in string contexts convert via the toString() method, which is different from String objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.
Upvotes: 0
Reputation: 21
It is obj.valueOf()
if I'm not mistaken. Here is the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
Upvotes: 2
Reputation: 1
If you need the name 'maro' and the age 77, you need use obj.name and obj.age...
Upvotes: -1