Home > OS >  JavaScript object property with `get` accessor not in Object.keys()
JavaScript object property with `get` accessor not in Object.keys()

Time:12-19

Let's say I have a class with a public property with only a get accessor. I want to be able to loop through the object keys to process the object.

class Foo {
    get bar() {
        return 'barval';
    }
}

Why is bar not visible when I call Object.keys(...) (or similar functions) or looping through the keys in an object? new Foo().bar successfully returns barval when requested, but Object.keys(Foo) returns an empty array when I expected it to return ["bar"]. Why is this?

Sample output:

const foo = new Foo();
console.log(foo.bar,            // barval
    Object.keys(foo),           // []
    Object.entries(foo),        // []
    Object.values(foo));        // []
for (let key in foo)
    console.log(key, foo[key]); // Never reached

CodePudding user response:

Getters and setters aren't properties of the class instance so they aren't available in keys, entries or values.

They are instead members of the prototype of the class. You can iterate through the prototype, and just remove the likes of constructor to leave you with just those which you have declared in your class.

As far as I'm aware, the only way to do this would be:

var protoObj = Object.getOwnPropertyNames(foo.constructor.prototype);
for( var key in protoObj ) {
   console.log(protoObj[key]);
}

Returns:

constructor
bar

CodePudding user response:

You can use Object.getOwnPropertyDescriptors instead.

class Foo {
    get bar() {
        return 'barval';
    }
}
let o = Object.getOwnPropertyDescriptors(Foo.prototype);
console.log(o);
.as-console-wrapper{max-height:100%!important;top:0}

  • Related