Convert ES6 Class with Symbols to JSON

后端 未结 5 1873
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 23:31

I have hardcoded classes to represent models in my Aurelia application. Here\'s a model \'PostEdit\':

var _postID = Symbol();
var _title = Symbol();
var _te         


        
5条回答
  •  不知归路
    2020-12-09 00:08

    I'm assuming you're using symbols to keep the data private, but this means you're going to have to go through some extra steps if you want that data included in the JSON representation.

    Here's an example using toJSON on your model to explicitly export the properties you care about

    export class PostEdit {
    
      // ...
      toJSON() {
        return {
          postID: this.postID,
          title:  this.title,
          text:   this.text
        };
      }
    }
    

    Or

    export class PostEdit {
    
      // ...
      toJSON() {
        let {postID, title, text} = this;
        return {postID, title, text};
      }
    }
    

    When JSON.stringify is called on your instance, it will automatically call toJSON

提交回复
热议问题