Get object property name as a string

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

    You can wrap your property in a function and then convert the function to a string and get the property out of it.

    For example:

    function getPropertyName(propertyFunction) {
        return /\.([^\.;]+);?\s*\}$/.exec(propertyFunction.toString())[1];
    }
    

    Then to use it:

    var myObj = {
        myProperty: "testing"
    };
    
    getPropertyName(function() { myObj.myProperty; }); // myProperty
    

    Beware that minifiers could break this.

    Edit: I have created a compiler transform that works with babel and the typescript compiler (see ts-nameof). This is a much more reliable than doing something at runtime.

提交回复
热议问题