Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : class instantiation with json

I have a class "House" like :

class House{
    constructor(params){
       this.clear();
       // this = {...params} // I know that don't work !!!
       //--
       // if(params.address !== undefined) this.address = {...params.address}
       //...
    }

    clear(){
      this.address = {
         number: null,
         street: null,
         zipcode: null,
         ton: null,
      }
      this.access = {
         doorcode: null,
         stair: null,
      }
    }
}

I want to create a new instance of House and inject in constructor multiple json like :

const h = new House({address: { /* json */ }, access: { /* json */});

Or only one like :

const h = new House({access: { /* json */});

In constructor, am i obliged to check all values in "params" to insert in good properties (nested object)

I would like to avoid to create other classes like address and access and in the house constructor create new instance of each. What's the best practice ?

Regards

like image 635
Brice Chaponneau Avatar asked Apr 30 '26 03:04

Brice Chaponneau


1 Answers

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 object
console.log(new House())
// empty object
console.log(new House({}))
// partial object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' } }))
// empty sub-objects
console.log(new House({ address: {}, access: {} }))
// partial sub-objects
console.log(new House({ address: { number: 1, street: 'street' }, access: { doorcode: 321 } }))
// complete object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' }, access: { doorcode: 321, stair: 3 } }))
.as-console-wrapper{min-height:100%!important}
like image 129
Patrick Roberts Avatar answered May 02 '26 17:05

Patrick Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!