sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

Load Json to Object #160

Closed lafama closed 1 year ago

lafama commented 1 year ago

Is there a way to load this Json string

{
  '_id': '6358b8b90ec2ddd2ca67d0fa',
  'isActive': 'false',
  'code': 'code',
  'dateUpdated': '2022-11-25T12:21:37.794Z'
}

to an Object that has the isActive cast to a boolean, id cast to Mongodb ObjectId and dateUpdated cast to Date object so it becomes

{
  '_id': new ObjectId('6358b8b90ec2ddd2ca67d0fa'),
  'isActive': false,
  'code': 'code',
  'dateUpdated': new Date('2022-11-25T12:21:37.794Z')
}
sylvainpolletvillard commented 1 year ago

ObjectModel does not change the type of your data. If you need to apply custom casting rules like string to boolean or string to date, you need to define your own custom logic in a factory function or a class constructor.

function parseMyObject(json){
return MyModel ({
  _id: new ObjectId(json._id),
  isActive: json.isActive === "true",
  code: json.code,
  dateUpdated: new Date(json.dateUpdated)
})
}