Hi!
It was asked on this list how to iterate over a JS object.
Here is some code how to iterate over all properties of a
given JSValueConst map.
If this is wrong, or if it leaks memory, kindly correct me.
JSPropertyEnum *ptab;
uint32_t plen;
JS_GetOwnPropertyNames(ctx, &ptab, &plen, map, JS_GPN_STRING_MASK);
for (int i = 0; i < plen; i++) {
JSValue val = JS_GetProperty(ctx, map, ptab[i].atom);
// get the key
const char *keyS = JS_AtomToCString(ctx, ptab[i].atom);
// get the value (in this example I am only interested in values that are
string
if (JS_IsString(val)) {
const char *valS = JS_ToCString(ctx, val);
printf(" %s: k=%s, v=%s \n", comment, keyS, valS);
JS_FreeCString(ctx, valS);
} else {
printf(" %s: k=%s,value is not a String. Ignoring! \n", comment,
keyS);
}
JS_FreeCString(ctx, keyS);
JS_FreeAtom(ctx, ptab[i].atom);
}
free(ptab);
Cheers
- Guido