Skip to content
Related Articles

Related Articles

Improve Article

How to call the key of an object but returned as a method, not a string ?

  • Last Updated : 31 Mar, 2021

By default, object keys are returned as strings, but it is possible to return them as a method.

Steps are follows:

  • Get the object keys.
  • Assign function to the 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




<script>
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);
</script>

Output:

Example 2: The following code is implemented using Object.entries() and ‘new Function‘ .

Javascript




<script>
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);
</script>

Output:

object keys function




My Personal Notes arrow_drop_up
Recommended Articles
Page :