How to call the key of an object but returned as a method, not a string ?
Last Updated :
15 Feb, 2023
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 = {};
Object.keys(obj)
.forEach(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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...