Get object property name as a string

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

    I am in same situation.

    Here is thy way to get it done using Lodash or UnderScore library, with one limitation of value to be unique:

    var myObject = {
    'a': 1,
    'b': 2,
    'c': 3
    }
    _.findKey(myObject, function( curValue ) { return myObject.a === curValue });
    

    Plain JavaScript

    function getPropAsString( source, value ){
        var keys = Object.keys( source );
    
        var curIndex,
            total,
            foundKey;
    
        for(curIndex = 0, total = keys.length; curIndex < total; curIndex++){
            var curKey = keys[ curIndex ];
            if ( source[ curKey ] === value ){
                foundKey = curKey;
                break;
            }
        }
    
        return foundKey;
    }
    
    var myObject = {
    'a': 1,
    'b': 2,
    'c': 3
    }
    getPropAsString( myObject, myObject.a )
    

    But, I would prefer to fix the code as solution. An example:

    var myObject = {
    'a': {key:'a', value:1},
    'b': {key:'b', value:2},
    'c': {key:'c', value:3}
    }
    
    console.log( myObject.a.key )
    

提交回复
热议问题