There's no reasonable way for the function you've called to know the name of the property referring to it. You'll need to change your structure if you want that. One way to do that is to bind the name of the function to it as its first argument:
const json = {
'keyone' : function (name) {
console.log(name);
} ,
'keytwo' : function (name) {
console.log(name);
}
};
for (const [key, func] of Object.entries(json)) {
json[key] = func.bind(null, key);
}
json.keyone(); // "keyone"
json.keytwo(); // "keytwo"
The unreasonable way to do it without changing your structure, which won't work in strict mode and which I do not recommend, is to use arguments.callee.name
in a modern browser. In a modern browser, your functions have names (they get their name from the property you're assigning them to). The deprecated arguments.callee
property gives you a reference to the called function, and you can get its name
from that:
const json = {
'keyone' : function () {
console.log(arguments.callee.name);
} ,
'keytwo' : function () {
console.log(arguments.callee.name);
}
};
json.keyone();
json.keytwo();
But again, I strongly recommend changing your structure instead. callee
is deprecated, and doesn't work in strict mode, and older browsers (ones that don't support ES2015's implied function names) don't assign the function name.