DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 4: Polyfill for Object.keys()

Today, we'll create a polyfill for the Object.keys() method. The Object.keys() method returns an array of a given object's own enumerable property names. Our goal is to create a function called myKeys that will implement this behavior.

// Test case
const obj = { name: "Bob", age: 1000 };
console.log(Object.myKeys(obj)); // Output: ["name", "age"]
Enter fullscreen mode Exit fullscreen mode

Plan

To solve this problem, we'll follow these steps:

  • Implement the myKeys function to retrieve the enumerable property names of the object.
  • Use a loop or a built-in method to iterate over the object's properties and collect the keys.
  • Return an array containing the collected keys.
  • Check if the Object.myKeys property exists.
  • If it doesn't exist, create a new property called myKeys on Object and assign it a function.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan

// Check if Object.myKeys exists
if (!Object.myKeys) {
  Object.myKeys = function (obj) {
    // Create an array to store the keys
    const keys = [];

    // Iterate over the object's properties
    for (let key in obj) {
      // Check if the property belongs to the object and is not inherited
      if (obj.hasOwnProperty(key)) {
        // Add the key to the keys array
        keys.push(key);
      }
    }

    return keys;
  };
}

// Test case
const obj = { name: "Bob", age: "1000" };
console.log(Object.myKeys(obj)); // Output: ["name", "age"]
Enter fullscreen mode Exit fullscreen mode