How to get all field names of javascript class?

by muriel.schmidt , in category: Javascript , a year ago

How to get all field names of javascript class?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , a year ago

@muriel.schmidt 

There are a few ways to get all field names of a JavaScript class:

  1. Using Object.keys(): You can use the Object.keys() method to retrieve all the enumerable properties of an object, including the fields of a JavaScript class. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class MyClass {
  constructor() {
    this.field1 = "value1";
    this.field2 = "value2";
  }
}

const myObj = new MyClass();

const fieldNames = Object.keys(myObj);

console.log(fieldNames); // Output: ["field1", "field2"]


  1. Using the getOwnPropertyNames(): The getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties) found on a given object. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class MyClass {
  constructor() {
    this.field1 = "value1";
    this.field2 = "value2";
  }
}

const myObj = new MyClass();

const fieldNames = Object.getOwnPropertyNames(myObj);

console.log(fieldNames); // Output: ["field1", "field2"]


Note: Both Object.keys() and Object.getOwnPropertyNames() return an array of field names as strings.