Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

51
Views
Private fields in Javascript don't show up in JSON.stringify

So if I write a class as follows

class Rectangle {
   #width;
   #height;
   constructor() {
      this.#width = 3;
      this.#height = 5; 
   }

}

let rect = new Rectangle();

console.log(JSON.stringify(rect)); // returns {}

It will return an empty object, totally ignoring all of my private members. Adding a toJSON method works but that becomes very cumbersome. Is there any built-in way that I can easily get my private fields to show up in JSON.stringify? Or do I just have to write in every single member into a toJSON method?

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Private properties are only accessible inside the class declaration itself. You'll need to write your own serialization method:

class Rectangle {
  #width;
  #height;
  constructor() {
    this.#width = 3;
    this.#height = 5;
  }

  stringify() {
    return JSON.stringify({['#width']: this.#width,['#height']: this.#height})
  }

}

let rect = new Rectangle();

console.log(rect.stringify())

7 months ago · Juan Pablo Isaza Report

0

One option to avoid having to write out all the members would be to have a single private data property on the instance, and then serialize / deserialize that property:

class Rectangle {
   #data;
   constructor(data) {
      this.#data = data;
   }
   getWidth = () => this.#data.width;
   toJson = () => JSON.stringify(this.#data);
}
const r = new Rectangle({ width: 1, height: 1 });
console.log(r.getWidth());
const stringified = r.toJson();
console.log(stringified);

const restructured = new Rectangle(JSON.parse(stringified));
console.log(restructured.getWidth());

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs