Saturday, November 23, 2024
Google search engine
HomeLanguagesJavascriptHow to call the key of an object but returned as a...

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

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments