How to access the first property of a Javascript object?

前端 未结 19 2881
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 09:00

Is there an elegant way to access the first property of an object...

  1. where you don\'t know the name of your properties
  2. without using a loop like
19条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:36

    I don't recommend you to use Object.keys since its not supported in old IE versions. But if you really need that, you could use the code above to guarantee the back compatibility:

    if (!Object.keys) {
    Object.keys = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;
    
    return function (obj) {
      if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
    
      var result = [];
    
      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }
    
      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    }})()};
    

    Feature Firefox (Gecko)4 (2.0) Chrome 5 Internet Explorer 9 Opera 12 Safari 5

    More info: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys

    But if you only need the first one, we could arrange a shorter solution like:

    var data = {"key1":"123","key2":"456"};
    var first = {};
    for(key in data){
        if(data.hasOwnProperty(key)){
            first.key = key;
            first.content =  data[key];
            break;
        }
    }
    console.log(first); // {key:"key",content:"123"}
    

提交回复
热议问题