In javascript the variables reference objects, but the objects themselves aren't named. So given an object, you can't really ask it for it's name; it doesn't make sense. When you think about how references are passed around in javascript you realize how problematic what you are attempting is in a general case. For example consider this:
var a = {first_name: "Mark"};
var b = a;
// a and b both point to the same object
If I ask for the name of that object, should it return a
, b
, or both? What about now:
var a = {first_name: "Mark"};
var b = a;
a = undefined;
This is even more complicated when you consider that the same object can be referenced by names in different scopes and modules. For example:
var a = {first_name: "Mark"};
function test(obj) {
var t = obj;
getNames(obj) // <-- what should that return? a? obj? t? all of them?
}
Give a particular scope, you could iterate through the names and find the ones that equal your object, but this is going to be fragile and probably inefficient.
var a = {first_name: "Mark"}
var b = a
var c = {foo: "bar"}
function getNames(obj, scope) {
for (name in scope){
try {
if (scope[name] === obj) console.log(name)
} catch(e){continue} // avoid localStorage security error
}
}
getNames(b, this) // should log 'a' and 'b' because both are in global scope
But again the above code does not really give you the name of the object, it just looks at every name in a particular object (in this case the global object) and and sees which of the object's properties point to the object in question.
Of course not all objects that are in scope even have names. For example::
let arr = [{foo: "bar"}, {foo: "baz"}]
getNames(arr[0]) // <-- what should that return?
If the name of the object is important and you want to display it, you should add a name property to the object and use it instead.