Reputation: 1019
I have this code:
<script type="module">
const _Tasks = {};
const _client = {};
const _client_simple = {};
const _status = {};
const _status_simple = {};
//need here a function to get all above declared and defined objects in a loop
</script>
I am trying to get all the above declared and defined objects in a loop.
I have tried this way:
const objects = Object.getOwnPropertyNames(this);
objects.forEach(objectName => {
console.log(objectName);
});
But this is undefined.
Is this possible and how?
Upvotes: 1
Views: 89
Reputation: 7616
Short answer: JavaScript has no concept of querying the list of variables defined as const
or let
.
You can however query the list of variables defined with var
because they are attached to the window
object. This is the windowKeys
example below.
If you want to query the variables why not adding them to an object? This is the myObjectKeys
example below.
var _Tasks = {};
var _client = {};
var _client_simple = {};
var _a_number = 123;
var _a_string = "hello";
var _a_boolean = true;
const windowKeys = Object.keys(window).filter(key => /^_/.test(key));
console.log('windowKeys:');
windowKeys.forEach(key => {
console.log(' ' + key + ', type: ' + typeof window[key]);
});
const myObject = {
_Tasks: {},
_client: {},
_client_simple: {},
_a_number: 123,
_a_string: "hello",
_a_boolean: true
}
const myObjectKeys = Object.keys(myObject);
console.log('myObjectKeys:');
windowKeys.forEach(key => {
console.log(' ' + key + ', type: ' + typeof myObject[key]);
});
Output:
windowKeys:
_Tasks, type: object
_client, type: object
_client_simple, type: object
_a_number, type: number
_a_string, type: string
_a_boolean, type: boolean
myObjectKeys:
_Tasks, type: object
_client, type: object
_client_simple, type: object
_a_number, type: number
_a_string, type: string
_a_boolean, type: boolean
Upvotes: 1
Reputation: 943999
JavaScript provides no mechanisms for determining what variables exist.
If you need to programmatically inspect a group of data, then you need to express that data as a group in the first place (e.g. as properties of an object that you can iterate through) instead of as individual variables.
If, on the other hand, this is just for debugging purposes, then pausing execution in the module (e.g. with a breakpoint) will cause most debugging tools to display the variables in scope.
Upvotes: 3