Get object property name as a string

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

    You can accomplish this by converting all object properties into functions which will return the their own names

    var person = {};
    person.firstname = 'Jack';
    person.address = "123 Street";
    
    function getPropertyName(obj, expression) {
        var res = {};
        Object.keys(obj).map(k => { res[k] = () => k; });
        return expression(res)();
    }
    
    let result = getPropertyName(person, o => o.address);
    console.log(result); // Output: 'address'
    
    0 讨论(0)
  • 2020-12-04 19:20

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 19:20

    No, it's not possible.

    Imagine this:

    person.age = 42;
    person.favoriteNumber = 42;
    
    var pn = propName(person.age)
    // == propName(42)
    // == propName(person.favoriteNumber);
    

    The reference to the property name is simply lost in that process.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 19:21

    I like one liners, here's a generic solution:

    const propName = (obj,type) => Object.keys(obj).find(key => obj[key] === type)
    
    propName(person, person.age)
    
    0 讨论(0)
提交回复
热议问题