Search code examples
javascriptfunctiontemplate-literals

How do I generate getters and setters dynamically in JS?


I have an object with some properties and I want to loop though and generate getters for each, Any ideas ? Without using Proxy?

const obj = {
  _count1: 0,
  _count2: 23,
  _count3: 1,
};

for (const key in object) {
  if (Object.hasOwnProperty.call(object, key)) {
    // ?
   }
  }
}

Like this

const x = {
  _count: 0,
  get count() {
     return this._count;
  }
}

Solution

  • something like this?

    const obj = {
      _count1: 0,
      _count2: 23,
      _count3: 1,
    };
    
    for (const [key, value] of Object.entries(obj))
      Object.defineProperty(obj, key.slice(1), {
          get () { return obj[key]; },
          set (value) { obj[key] = value; }
      });
    
    obj.count2 = 34;
    console.log(obj.count2)