Ricardo Peres
Ricardo Peres

Reputation: 14535

How to List Properties Defined with Object.defineProperty

Is it possible to list all properties defined using Object.defineProperty? These don't show up while iterating through the object:

for (var prop in obj) { ... }

And neither with Object.getOwnPropertyNames.

Update: I guess it is only possible if they are created with the enumerable: true flag set.

Upvotes: 2

Views: 484

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Non-enumerable properties are returned by Object.getOwnPropertyNames:

var obj = {};
Object.defineProperty(obj, "foo", {value:42});
document.body.innerHTML = Object.getOwnPropertyNames(obj).join(", ");

If you define them with Symbol rather than string names, you'd use Object.getOwnPropertySymbols.

If you need to find non-enumerable inherited properties, you have to loop up your prototype chain via Object.getPrototypeOf.

Here's an example of finding all property names that are strings, regardless of whether they're enumerable, including inherited ones (note that we see the non-enumerables on Object.prototype; we could stop earlier if we didn't want them):

var proto = {}
Object.defineProperty(proto, "answer", {value: 42});
var obj = Object.create(proto);
Object.defineProperty(obj, "question", {value: "Life, the Universe, and Everything"});

document.body.innerHTML = getAllPropertyNames(obj).join(", ");

function getAllPropertyNames(o) {
  var names = [];
  while (o) {     // We'd use `o != Object.prototype` to stop earlier
    names.push.apply(names, Object.getOwnPropertyNames(o));
    o = Object.getPrototypeOf(o);
  }
  return names;
}

Upvotes: 6

Related Questions