Javascript 以字符串形式获取对象属性名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13612006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get object property name as a string
提问by CLiFoS
Is it possible to get the object property name as a string
是否可以将对象属性名称作为字符串获取
person = {};
person.first_name = 'Hyman';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';
I'd like to use it like this:
我想像这样使用它:
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.
注意:此代码正是我正在寻找的。我明白这听起来很愚蠢,但事实并非如此。
This is what I want to do with it.
这就是我想要做的。
HTML
HTML
person = {};
person.id_first_name = 'Hyman';
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-----------------------
--------------答案--------------
Got it thanks to ibu. He pointed the right way and I used a recursive function
感谢 ibu 得到它。他指出了正确的方法,我使用了递归函数
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'
采纳答案by Ibu
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";
NoteI am not sure what it can be used for.
注意我不确定它可以用来做什么。
Other Notewont work very well with nested objects. but then again, see the first note.
其他注释不适用于嵌套对象。但话说回来,请参阅第一个注释。
回答by Triet Nguyen
I know a best practice that using Object.keys(your_object). It will parse to array property name for you. Example:
我知道使用Object.keys(your_object)的最佳实践。它将为您解析为数组属性名称。例子:
var person = { firstName: 'John', lastName: 'Cena', age: '30' };
var listPropertyNames = Object.keys(person); //["firstName", "lastName", "age"]
I hope this example is useful for you.
我希望这个例子对你有用。
回答by artemdev
You can accomplish this by converting all object properties into functions which will return the their own names
您可以通过将所有对象属性转换为函数来实现此目的,这些函数将返回它们自己的名称
var person = {};
person.firstname = 'Hyman';
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'
回答by David Sherret
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.
编辑:我创建了一个与 babel 和typescript编译器一起使用的编译器转换(请参阅ts-nameof)。这比在运行时做某事要可靠得多。
回答by Isk1n
Using Proxy:
使用代理:
var propName = ( obj ) => new Proxy(obj, {
get(_, key) {
return key;
}
});
var person = {};
person.first_name = 'Hyman';
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);
回答by Nimrod
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)
回答by Nimrod
Following up on @David Sherret's answer with ES6 it can be made super simple:
用 ES6 跟进@David Sherret 的回答,它可以变得非常简单:
propName = f => /\.([^\.;]+);?\s*\}$/.exec(f.toString())[1]
let prop = propName(() => {obj.name}); // myProperty
回答by Scott Sauyet
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.
在该过程中,对属性名称的引用只是丢失了。
回答by David Hellsing
You could create a namespacing method for the object. The method will need to mutate the object so that the strings becomes an object instead to hold two properties, a valueand a _namespace.
您可以为对象创建命名空间方法。该方法需要改变对象,以便字符串成为一个对象,而不是保存两个属性 avalue和 a _namespace。
DEMO: http://jsfiddle.net/y4Y8p/1/
演示:http: //jsfiddle.net/y4Y8p/1/
var namespace = function(root, name) {
root._namespace = name;
function ns(obj) {
for( var i in obj ) {
var a = obj._namespace.split('.')
if ( a.length ) {
a.push(i);
}
if( typeof obj[i] == 'object' ) {
obj[i]._namespace = a.join('.');
ns(obj[i]);
return;
}
if( typeof obj[i] == 'string' ) {
var str = obj[i].toString();
obj[i] = {
_namespace: a.join('.'),
value: str
};
}
}
}
ns(root);
};
namespace(person, 'person');
console.log(person.address.street._namespace) // person.address.street
console.log(person.address.street.value) // 'Factory 1'
So now you can do:
所以现在你可以这样做:
var o = { message: MSG_ACTION };
o[ person.first_name._namespace ] = person.first_name.value;
extPort.postMessage(o);
回答by Maximilian Fixl
I prefer it clean and simple like this:
我更喜欢像这样干净简单:
var obj = {
sessionId: 123,
branchId: 456,
seasonId: 789
};
var keys = Object.keys(obj);
for (var i in keys) {
console.log(keys[i]); //output of keys as string
}

