Get object property name as a string

后端 未结 13 557
难免孤独
难免孤独 2020-12-04 18:40

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

person = {};
person.first_name = \'Jack\';
person.last_name = \'Trades\';
person.address = {};
per         


        
13条回答
  •  伪装坚强ぢ
    2020-12-04 19:21

    Yes you can, with a little change.

    function propName(prop, value){
       for(var i in prop) {
           if (prop[i] == value){
                return i;
           }
       }
       return false;
    }
    

    Now you can get the value like so:

     var pn = propName(person,person.first_name);
     // pn = "first_name";
    

    Note I am not sure what it can be used for.

    Other Note wont work very well with nested objects. but then again, see the first note.

提交回复
热议问题