Javascript : class instantiation with json
Using Object.assign()
and object destructuring with default parameters in the constructor
, you can achieve this quite easily:
class House { static get defaultAddress () { return { number: null, street: null, zipcode: null, town: null } } static get defaultAccess () { return { doorcode: null, stair: null } } constructor({ address = House.defaultAddress, access = House.defaultAccess } = {}) { this.clear() Object.assign(this.address, address) Object.assign(this.access, access) } clear () { const { defaultAddress, defaultAccess } = House Object.assign(this, { address: defaultAddress, access: defaultAccess }) }}// no objectconsole.log(new House())// empty objectconsole.log(new House({}))// partial objectconsole.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' } }))// empty sub-objectsconsole.log(new House({ address: {}, access: {} }))// partial sub-objectsconsole.log(new House({ address: { number: 1, street: 'street' }, access: { doorcode: 321 } }))// complete objectconsole.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' }, access: { doorcode: 321, stair: 3 } }))
.as-console-wrapper{min-height:100%!important}
You can loop through the parameters and set them manually. Then, to clear, remove all own properties (properties that aren't inherited).
class House { constructor(params) { // set data Object.assign(this, params); } clear() { for (let key in this) { if (this.hasOwnProperty(key)) this[key] = undefined; // or `delete this[key];` } }}let house = new House({type: "normal", height: 40});console.log(house, house instanceof House);
Of course, you probably want to limit the input keys to a predefined set. You could store those keys in a static class variable and use them to loop through the properties in constructor
and clear
.
class House { constructor(params) { // check for invalid properties Object.keys(params).forEach(key => { if (!House.keys.includes(key)) throw `Invalid paramater ${key}`; }); // set data Object.assign(this, params); } clear() { for (let key in House.keys) { if (this.hasOwnProperty(key)) this[key] = undefined; // or `delete this[key];` } }}House.keys = ['type', 'height'];let house = new House({type: 'normal', height: 40});console.log(house, house instanceof House);let error = new House({helloWorld: true});
I think you want a common namespace for your instance properties - similar to React's props
pattern - you can also specify defaults for each instance you are creating:
const defaultProps = { address: {}, access: {} };class House { constructor(props = {}) { this.props = {...defaultProps, ...props}; } clear() { this.props = {...defaultProps}; }}