0

Tell me please how to convert a class (with members and methods) into an array containing only some members and their values most correctly

class MyObject {
   member1: 10;
   member2: "test";
   member3: true;

   method() {
      console.log(member2);
      return member1;
   }
}

after conversion:

data = {
    member2: "test",
    member3: true
}

My algorithm seems to me not to be very successful:

let object: MyObject= new MyObject();

const entries: any = Object.entries(object);

const data: Array<any> = entries.filter((element: any) => (element[0] !== "member1"));

let result;

data.forEach((element: any) => result[element[0]] = element[1]);

Please prompt a shorter and more elegant way.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Zhihar
  • 1,306
  • 1
  • 22
  • 45
  • You may find elegant solutions under the topic Serialization https://stackoverflow.com/questions/29758765/json-to-typescript-class-instance – pce Sep 16 '20 at 15:27
  • To me, shorter != more elegant. Please identify objective criteria by which answers will be judged. Otherwise this question lends itself to opinions rather than facts. – Heretic Monkey Sep 16 '20 at 15:35
  • Does this answer your question? [How to get a subset of a javascript object's properties](https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties) (without any notion of shorter or more elegant) – Heretic Monkey Sep 16 '20 at 15:37
  • @Heretic Monkey: more efficient, contains fewer commands/actions, runs faster, spends less memory, but the main criterion is that it does not contain any unnecessary commands/actions. – Zhihar Sep 16 '20 at 16:03

0 Answers0