JS: Object.keys

By Xah Lee. Date: . Last updated: .
Object.keys(obj)

Return a Array of property keys that are own, string, and Enumerable.

console.log(Object.keys({ cat: 3, dog: 4 }));
// [ "cat", "dog" ]
// example on array
console.log(Object.keys([3, 4, 5]));
// [ "0", "1", "2" ]
// verify the result is true array
console.assert(
 Array.isArray(Object.keys({ cat: 3, dog: 4 })),
);

Test. ignore symbol keys

The following example shows that Symbol key and non-enumerable properties are ignored.

// create a object, such that only 1 property is both enumerable and string key

const xx = Object.create(Object.prototype, {
 "dog": {
  value: 3,
  writable: true,
  enumerable: true,
  configurable: true,
 },
 "cat": {
  value: 3,
  writable: true,
  enumerable: false,
  configurable: true,
 },
 [Symbol("x")]: {
  value: 3,
  writable: true,
  enumerable: true,
  configurable: true,
 },
});

const yy = Object.keys(xx);

console.assert(yy.length === 1);
console.assert(yy[0] === "dog");