以字符串形式获取对象属性名称 [英] Get object property name as a string

查看:36
本文介绍了以字符串形式获取对象属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将对象属性名称作为字符串获取

Is it possible to get the object property name as a string

person = {};
person.first_name = 'Jack';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';

我想这样使用它:

var pn = propName( person.address.country ); // should return 'country' or 'person.address.country'
var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name'

注意:这段代码正是我要找的.我知道这听起来很愚蠢,但事实并非如此.

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

这就是我想要的.

HTML

person = {};
person.id_first_name = 'Jack';
person.id_last_name = 'Trades';
person.address = {};
person.address.id_address = 'Factory 1';
person.address.id_country = 'USA';


extPort.postMessage
(
  {
    message : MSG_ACTION,
    propName( person.first_name ): person.first_name
  }
};

----------------------答案-----------------------

----------------------ANSWER-----------------------

感谢 ibu.他指出了正确的方法,我使用了递归函数

Got it thanks to ibu. He pointed the right way and I used a recursive function

var res = '';

function propName(prop, value) {
    for (var i in prop) {
        if (typeof prop[i] == 'object') {
            if (propName(prop[i], value)) {
                return res;
            }
        } else {
            if (prop[i] == value) {
                res = i;
                return res;
            }
        }
    }
    return undefined;
}

var pn = propName(person, person.first_name); // returns 'first_name'
var pn = propName(person, person.address.country); // returns 'country'

演示:http://jsbin.com/iyabal/1/edit

推荐答案

是的,只需稍作改动即可.

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.

这篇关于以字符串形式获取对象属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆