JavaScript:获取对象的第一个也是唯一的属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6765864/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:06:30  来源:igfitidea点击:

JavaScript: Get first and only property name of object

javascriptobjectproperties

提问by FoobarisMaximus

If I want to enumerate the properties of an object and want to ignore prototypes, I would use:

如果我想枚举一个对象的属性并想忽略原型,我会使用:

var instance = { ... };

for (var prop in instance) {
    if (instance.hasOwnProperty(prop)) {
        ... 
    }
}

What if instanceonly has one property, and I want to get that property name? Is there an easier way than doing this:

如果instance只有一个属性,而我想获得该属性名称怎么办?有没有比这样做更简单的方法:

var instance = { id: "foobar" };

var singleMember = (function() {
    for (var prop in instance) {
        if (instance.hasOwnProperty(prop)) {
            return prop;
        }
    }
})();

回答by KooiInc

Maybe Object.keyscan work for you. If its length returns 1, you can use yourObject[Object.keys[0]]to get the only property of the object. The MDN-link also shows a custom function for use in environments without the keysmethod1. Code like this:

也许Object.keys可以为您工作。如果其长度返回 1,则可以使用yourObject[Object.keys[0]]来获取对象的唯一属性。MDN-link 还显示了在没有keys方法1 的环境中使用的自定义函数。像这样的代码:

var obj = {foo:'bar'}, 
    kyz = Object.keys(obj);
if (kyz.length === 1){
   alert(obj[kyz[0]]); //=> 'bar'
} else {
  /* loop through obj */
}

1Some older browsers don't support Object.keys. The MDN link supplies code to to make it work in these browsers too. See header Compatibilityin the aforementioned MDN page

1一些较旧的浏览器不支持Object.keys. MDN 链接提供了使其在这些浏览器中也能工作的代码。请参阅上述MDN 页面中的标题兼容性

回答by Isaac Han

Shortest form:

最短形式:

instance[Object.keys(instance)[0]];

ES6+ function:

ES6+功能:

let first = v => v[Object.keys(v)[0]];

Use the function:

使用函数:

first({a:'first', b:'second'}) // return 'first'

回答by shabunc

Though my answer is downvoted, it's still worth to know that there is nosuch thing as order of keys in javascript object. Therefore, in theory, any code build on iterating values can be inconsistent. One approach could be creating an object and to define setter which actually provides counting, ordering and so on, and provide some methods to access this fields. This could be done in modern browsers.

虽然我的回答被否决了,但仍然值得知道在 javascript 对象中没有键的顺序这样的东西。因此,理论上,任何基于迭代值构建的代码都可能不一致。一种方法是创建一个对象并定义实际提供计数、排序等功能的 setter,并提供一些访问这些字段的方法。这可以在现代浏览器中完成。

So, to answer you question, in general you approach is still most closs-browser. You can iterate using lodash or any other modern framework wich will hide "hasOwnProperty" complexity from you. As of August'15 Object.keyscan be accepted as cross-browser and universal. After all IE8 happened years ago. Still there are some cases when you just don't wont store all set of keys in array. But I'd go with Object.keys - it's more flexible compared to iteration.

所以,回答你的问题,一般来说你的方法仍然是最接近的浏览器。您可以使用 lodash 或任何其他现代框架进行迭代,这将隐藏“hasOwnProperty”的复杂性。截至 August'15Object.keys可以被接受为跨浏览器和通用。毕竟 IE8 发生在几年前。在某些情况下,您只是不会将所有键集存储在数组中。但我会选择 Object.keys - 与迭代相比,它更灵活。

回答by cwallenpoole

Unfortunately, there is no, "list properties" function built in, and there certainly isn't a "getFirstProperty" (especially since there is no guarantee that any property will consistently be "first").

不幸的是,没有内置的“列表属性”函数,当然也没有“getFirstProperty”(特别是因为不能保证任何属性始终是“第一”)。

I think you're better off writing a function like this one:

我认为你最好写一个这样的函数:

/**
 * A means to get all of the keys of a JSON-style object.
 * @param obj The object to iterate
 * @param count maximum length of returned list (defaults to Infinity).
 */
function getProperties( obj, count )
{
    if( isNaN( count ) ) count = Infinity
    var keys = []
    for( var it in obj )
    {
        if( keys.length > count ) break;
        keys.push( it );
    }
    return keys;
}

Then, you could access the name though:

然后,您可以访问该名称:

instance = {"foo":"bar"}
// String() on an array of < 2 length returns the first value as a string
// or "" if there are no values.
var prop = String(getProperties(instance, 1));

回答by mewc

  var foo = {bar: 1};
  console.log(Object.keys(foo).toString());

which will print the string

这将打印字符串

"bar"

回答by Andrew

This is an old post, but I ended up writing the following helper function based on Object.keys().

这是一篇旧帖子,但我最终基于Object.keys()编写了以下辅助函数。

It returns the keyand valueof the first property.

它返回第一个属性的keyvalue

getFirstPropertyKeyAndValue(sourceObject) {
    var result = null;
    var ownProperties = Object.keys(sourceObject);
    if (ownProperties.length > 0) {
      if (ownProperties.length > 1) {
        console.warn('Getting first property of an object containing more than 1 own property may result in unexpected results. Ordering is not ensured.', sourceObject);
      }
      var firstPropertyName = ownProperties[0];
      result = {key: firstPropertyName, value: sourceObject[firstPropertyName]};
    }
    return result;
  }