Get object property name as a string

后端 未结 13 603
难免孤独
难免孤独 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:32

    I am late to the party but I took a completely different approach, so I will throw in my approach and see what the community thinks.

    I used Function.prototype.name to do what I want. my properties are functions that when called return the value of the property, and I can get the name of the property (which is a function) using .name

    Here is an example:

    person = {
        firstName(){
            return 'John';
        },
        address(){
            return '123 street'
        }
    }
    
    person.firstName.name // 'firstName'
    person.address.name // 'address'
    

    Note:
    you can't easily change the value of a property (e.g firstname) at run time in this case. you would need to create a function (.name would be anonymous in this case) and this function would return a new named function which return the new value:

    // note the () at the end     
    person.firstName = new Function('', 'return function firstName(){return "johny"}')(); 
    person.firstName.name ; // 'firstName' 
    person.firstName(); // 'johny'
    

提交回复
热议问题