Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get object's name in javascript?

For example I have such an object:

var a = {
    'light': 'good',
    'dark' : {
        'black': 'bad',
        'gray' : 'not so bad'
    }
}

and such a code:

var test = function(obj) {
    // do smth with object
    // I need to get obj's name ('dark' in my way)
}
test(a.dark);

How to get name of object in function's body. So I mean I should know that obj's name is 'dark'.

I've tried inspect object with firebug, but it's only show object's property. It's not showing some internal methods or properties, with which I'll be able to know

Thank you.

like image 518
Larry Cinnabar Avatar asked Mar 27 '11 08:03

Larry Cinnabar


People also ask

How can we get name and type of any object?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

How do you get the properties name of an object in typescript?

getPropName('yourPropName') to get the property name.

What is object object in JavaScript?

The Object type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.


1 Answers

You can't. You're only passing the object { black : 'bad', gray : 'not so bad' } into test. This object does not intrinsically have the name "dark", it's just an object that happened to exist as the property dark of the object a. This information is irretrievably lost when passing it into a function.

You're basically trying to retrieve the variable name that held the value before the value got passed into the function. That's not possible.

like image 57
deceze Avatar answered Sep 30 '22 15:09

deceze