By default, object keys are returned as strings, but it is possible to return them as a method.
The steps are follows:
- Get the object keys.
- Assign function to every key.
- Assign them to an object.
- Return the object.
Example 1: The above approach is implemented using JavaScript functions Object.keys() and forEach().
Javascript
let person = {     name : "Raktim Banerjee",       email: "example@gmail.com"}   const getObjectKeyAsMethod = obj =>{  let newObject = {};     //returned object keys in an array  Object.keys(obj)      //iterate the array     .forEach(key => {       //assign function to key       newObject[key] = function(){}   })  return newObject; }   let result = getObjectKeyAsMethod(person);   console.log(result); |
Output:
Example 2: The following code is implemented using Object.entries() and ‘new Function‘ .
Javascript
let person = { Â Â Â Â name : "Raktim Banerjee", Â Â Â Â email: "example@gmail.com"} Â Â let result = {} for(let [key] of Object.entries(person)){ Â Â Â Â result[key] = new Function() } Â Â console.log(result); |
Output:
object keys function
