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

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

问题描述

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

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天全站免登陆