-1

Is there a way to tell the stringify method to convert an object to a primitive datatype?

class Bar {
    constructor() {
        this.name = 'bar';
    }
}

const obj = {foo: new Bar};

JSON.stringify(obj);

// output:        '{foo: {name: 'bar'}}'
// wanted output: '{foo:'bar'}'

I've tried overriding toSting and valueOf methods but with no results

Bar.prototype.toString = function() {
    return this.name;
}

Bar.prototype.valueOf = function() {
    return this.name;
}

Slev7n
  • 343
  • 3
  • 14
  • 2
    add a [`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior) to your class, that returns "bar". – ASDFGerte Jul 16 '22 at 21:34

1 Answers1

2

Add toJSON prototype method in Bar class.

Bar.prototype.toJSON = function() {
    return this.name;
}
hotbrainy
  • 331
  • 1
  • 10