1

Is there a way I can get all the getters results on the instance without specific invoking? I want to get all class getters as simple members on the class by looping on the class member.

I have a class like this:

export class Test {
  constructor() {}

  get foo() {
    return 1
  }

  get bar() {
    return 2
  }
}

The use is create a new instance: const test = new Test()

Is there a way I can get all the getters as simple class variable members and not as functions? so I can pass the object from server to client.

Thanks!

ESI
  • 1,657
  • 8
  • 18
  • 1
    Hard to tell what you're asking or which part you're having trouble with. You can just call the getters yourself. You should explain more about what you're doing an HR house you're sending the data to the server. You can also implement a toJson method to be used with JSON.stringify See https://stackoverflow.com/a/42107611/227299 – Ruan Mendes Dec 21 '21 at 00:01
  • What do you mean by "*without specific invoking*"? You cannot get the getter results without invoking them. – Bergi Dec 21 '21 at 00:12
  • @JuanMendes "*doing an HR house*"??? – Bergi Dec 21 '21 at 00:13
  • @Bergi Sorry, from a phone – Ruan Mendes Dec 21 '21 at 00:57

1 Answers1

0

class Test {
  constructor() {}

  get foo() {
     return 1
  }

  get bar() {
    return 2
  }
}

const allGetterKeys = Object.entries(Object.getOwnPropertyDescriptors(Test.prototype)).filter(([key, descriptor]) => typeof descriptor.get === 'function').map(([key]) => key);

const test = new Test();
const out = {};

for(const key of allGetterKeys)
{
  out[key] = test[key];
}

console.log(out);

The first line comes from this answer (it gets the key names of all the getters on the class). Then the for loop uses all those keys to get the output from the getter and put them into a plain object out. That object is just key value pairs.

User81646
  • 628
  • 4
  • 13