How Can I Get Console.log To Output The Getter Result Instead Of The String "[getter/setter]"?
Solution 1:
You can use console.log(Object.assign({}, obj));
Solution 2:
Use console.log(JSON.stringify(obj));
Solution 3:
You can define an inspect
method on your object, and export the properties you are interested in. See docs here: https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects
I guess it would look something like:
functionCls() {
this._id = 0;
Object.defineProperty(this, 'id', {
get: function() {
returnthis._id;
},
set: function(id) {
this._id = id;
},
enumerable: true
});
};
Cls.prototype.inspect = function(depth, options) {
return`{ 'id': ${this._id} }`
}
var obj = newCls();
obj.id = 123;
console.log(obj);
console.log(obj.id);
Solution 4:
Since Nodejs v11.5.0 you can set getters: true
in the util.inspect
options. See here for docs.
getters <boolean> | <string> If set to true, getters are inspected. If set to 'get', only getters without a corresponding setter are inspected. If set to 'set', only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. Default: false.
Solution 5:
I needed a pretty printed object without the getters and setters yet plain JSON produced garbage. For me as the JSON string was just too long after feeding JSON.stringify()
a particularly big and nested object. I wanted it to look like and behave like a plain stringified object in the console. So I just parsed it again:
JSON.parse(JSON.stringify(largeObject))
There. If you have a simpler method, let me know.
Post a Comment for "How Can I Get Console.log To Output The Getter Result Instead Of The String "[getter/setter]"?"