0

I want to create an array from existing values of class vars in typescript

Eg:

export class example{
  static readonly a = 'aval';
  static readonly b = 'bval';
static readonly c = 'cval';
}

TO

exampleArray = ['aval', 'bval', 'cval'];

Note: I want to make it like access all vars values of class in one go and put it in array not like [example.a]

1
  • 1
    I hope you are not using a class with only static class variables in your actual code. If that'd be the case then you should use a plain object instead. Commented Jul 27, 2021 at 11:17

2 Answers 2

2

Object.values(example) should work

Sign up to request clarification or add additional context in comments.

4 Comments

I don't think it will work, Because the question is how to make an array from class not object
@Wajid ... A class in JavaScript is an object too. Thus a class with just static properties has to be treated like an object; in this case one actually should use a plain object at first place.
class in JS actually a function and function is an object), so static properties of class becomes properties of function/object ⚆ _ ⚆. Please try it, you will see that it works
@Wajid console.log(class A{} instanceof Object) gives true though...
1
Object.values(SomethingClass);

Will give you an array of the values. But just FYI - I believe it only works for static class members.

To get class members that aren't static, you'd need to instantiate it first.

Object.values(new SomethingClass());

That would give you only the non-static members.

3 Comments

I don't think it will work, Because the question is how to make an array from class not object
@Wajid - it works, I tested it before answering :-)
@Wajid what makes you think a class is not also an object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.