Get object property name as a string

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

    Using Proxy:

    var propName = ( obj ) => new Proxy(obj, {
        get(_, key) {
            return key;
        } 
    });
    
    
    var person = {};
    person.first_name = 'Jack';
    person.last_name = 'Trades';
    person.address = {};
    person.address.street = 'Factory 1';
    person.address.country = 'USA';
    
    console.log(propName(person).first_name);
    console.log(propName(person.address).country);

    0 讨论(0)
提交回复
热议问题