简体   繁体   中英

How to get the name of a specific Javascript property?

Given a Javascript object with the method myobject.mymethod the name of the method can be retrieved for printing or whatever using myobject.mymethod.name .

How do I achieve the same thing for property myobject.myproperty .

UPDATE: Specific scenario.

I have an object from a third party library that defines a load of constant values used throughout its api

obj = {
  CONST1 = 1;
  CONST2 = 2;
  CONST3 = 3;
  // ...
}

I'm handling events that are called with these values and want to log what each event is called with. The raw values aren't useful in a log, so I want to log the constant names, ideally without a switch statement mapping values to hardcoded strings or having to define my own lookup table.

The library object has a load of other crap defined on it too, so just looking up the property using the value is not a reliable solution.

You can list your properties with Object.keys(). So for example if you need list of props with their values, you can do something like this:

 let a = {prop: "foo"}; console.log( Object.keys(a) ); // prints all prop names Object.keys(a).map( (i) => console.log("property:", i, " has value: ", a[i]) ); // prints all props with corresponding values

Updated answer: Use debugger to find out which values are used inside program. https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM