Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object property name as a string

Is it possible to get the object property name as a string

person = {}; person.first_name = 'Jack'; person.last_name = 'Trades'; person.address = {}; person.address.street = 'Factory 1'; person.address.country = 'USA'; 

I'd like to use it like this:

var pn = propName( person.address.country ); // should return 'country' or 'person.address.country' var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name' 

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

This is what I want to do with it.

HTML

person = {}; person.id_first_name = 'Jack'; person.id_last_name = 'Trades'; person.address = {}; person.address.id_address = 'Factory 1'; person.address.id_country = 'USA';   extPort.postMessage (   {     message : MSG_ACTION,     propName( person.first_name ): person.first_name   } }; 

----------------------ANSWER-----------------------

Got it thanks to ibu. He pointed the right way and I used a recursive function

var res = '';  function propName(prop, value) {     for (var i in prop) {         if (typeof prop[i] == 'object') {             if (propName(prop[i], value)) {                 return res;             }         } else {             if (prop[i] == value) {                 res = i;                 return res;             }         }     }     return undefined; }  var pn = propName(person, person.first_name); // returns 'first_name' var pn = propName(person, person.address.country); // returns 'country' 

DEMO: http://jsbin.com/iyabal/1/edit

like image 413
CLiFoS Avatar asked Nov 28 '12 18:11

CLiFoS


People also ask

Can an object property be a string?

Property keys must be strings or symbols (usually strings). Values can be of any type.

How do I find the name of an object property?

To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.

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

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .


1 Answers

I know a best practice that using Object.keys(your_object). It will parse to array property name for you. Example:

var person = { firstName: 'John', lastName: 'Cena', age: '30' }; var listPropertyNames = Object.keys(person); //["firstName", "lastName", "age"] 

I hope this example is useful for you.

like image 152
Triet Nguyen Avatar answered Sep 21 '22 09:09

Triet Nguyen