How to call the key of an object but return it as a method, not a string in JavaScript?


We can use the "Object.keys()" method to retrieve the keys of an object. However, instead of returning the keys as a string, we can wrap the call to "Object.keys()" in a function. This way, when we call the function, it will return the keys as a method, rather than a string.

Approach 1

You can use the Object.keys() method to get an array of the keys of an object, then use array notation or the [] operator to access the key as a property of the object.

Here is an example −

let obj = { key1: "value1", key2: "value2" };
let keys = Object.keys(obj);
let firstKey = keys[0];
console.log(obj[firstKey]); // "value1"

Approach 2

If you want to use the key as a method, you can use the obj[firstKey]() notation to call the method like this −

let obj = { key1: () => {console.log("key1 method")} };
let keys = Object.keys(obj);
let firstKey = keys[0];
obj[firstKey](); // "key1 method"

Working Code Snippet

Here is an complete working snippet of how to call the key of an object as a method, rather than a string −

const obj = {
   method1: () => { console.log("This is method 1.") },
   method2: () => { console.log("This is method 2.") }
}
const key = "method1";
obj[key](); // Output: "This is method 1."

In this example, we first create an object called obj with two keys, method1 and method2, that are both set to arrow functions that log a message to the console. Next, we create a variable called key and set it equal to the string “method1”.

By using square bracket notation (obj[key]), we can access the value of the key within the object, which in this case is a function. By adding the parentheses () to the end of the line, we are calling the function, which will execute the code within it and log “This is method 1.” to the console.

We could also replace the key variable with a variable that contains the key name and it will work the same way −

let method = "method1";
obj[method]();

This is a useful pattern when the key name is not known until runtime and we want to access the value in the object, in this case a function, and execute it.

Updated on: 16-Feb-2023

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements