Ask Your Question

How can array data be transformed into JSON using the identical class constructor instead of an object constructor?

asked 2023-01-28 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-11-09 19:00:00 +0000

djk gravatar image

To transform array data into JSON using the identical class constructor instead of an object constructor, we can use the toJSON() method. This method is automatically called when the object is passed through the JSON.stringify() function.

Inside the toJSON() method, we can create a new instance of the same class and pass it the necessary data from the original instance. Then we can return this new instance, and the JSON string will be created using its properties.

Here is an example:

class MyClass {
  constructor(data) { = data;

  toJSON() {
    return new MyClass(;

const myArray = [new MyClass(1), new MyClass(2), new MyClass(3)];
const jsonString = JSON.stringify(myArray);
console.log(jsonString);  // '[{"data":1},{"data":2},{"data":3}]'

In this example, we create an array myArray of instances of the MyClass class. We then call JSON.stringify() on the array, which automatically calls the toJSON() method on each instance.

Inside the toJSON() method, we create a new instance of MyClass with the same data property as the original instance. We then return this new instance. Finally, the JSON.stringify() function creates a JSON string using the properties of the new instance, resulting in a JSON array of objects with the data property.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2023-01-28 11:00:00 +0000

Seen: 1 times

Last updated: Nov 09 '22