'Finding enumerable properties more directly
I have the following which iterates through an object/array to print its enumerable properties:
const reg = /(?<num>hi)(there)/g;
const str = 'hithere';
let matches = Array.from(str.matchAll(reg)); // same thing as [...matches[;]]
for (let match of matches) {
for (let elem of match) {
console.log('**', elem);
}
}
The actual object looks like this:
[
'hithere'. // enumerable
'hi', // enumerable
'there', // enumerable
index: 0, // no
input: 'hithere', // no
groups: [Object: null prototype] { num: 'hi' } // no
], ...
Is there a more direct way to (1) get the enumerable properties in an object; or (2) test to see if an Object property is enumerable? I thought the following would work but it seems to always print true for me:
matches[0].propertyIsEnumerable('index'));
Solution 1:[1]
That's a very good question.
for ... of does not necessarily loop over all enumerable properties in an object the way that for ... in does. Javascript objects can define their own iterable protocol.
The booleans your getting from propertyIsEnumerable are correct.
So to answer your questions directly: (1) yes: a for... in loop (2) no: your test is working fine
const reg = /(?<num>hi)(there)/g;
const str = 'hithere';
let matches = Array.from(str.matchAll(reg)); // same thing as [...matches[;]]
for (let match in matches) {
for (let elem in matches[match]) {
console.log(elem, matches[match][elem]);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David |
