在JavaScript对象中迭代属性的最佳方法是什么?

时间:2015-01-02 14:40:20

标签: javascript

我有以下javaScript对象:

var theData = {
   "data": [
      {
         "name": "Event1",
         "start_time": "2015-01-15T22:00:00-0200",
         "end_time": "2015-01-16T07:00:00-0200",
         "timezone": "America/Sao_Paulo",
         "location": "Somewhere",
         "id": "824583590897935"
      },
      {
         "name": "Event2",
         "start_time": "2015-01-14T22:00:00-0200",
         "timezone": "America/Sao_Paulo",
         "location": "Somewhere",
         "id": "1522505051359796"
      }
   ],
   "paging": {
      "cursors": {
         "after": "MzA0MjY5OTI5NzgwODIz",
         "before": "ODI0NTgzNTkwODk3OTM1"
      },
      "next": "https://graph.facebook.com/v2.2/217733628398158/events?access_token=CAACEdEose0cBAAW4SjUBnZB9x1Y6euJS6Bbmky2ZBfyMJ7eq4hPyy0g6lrk9itZCS2Rf2vmAmlYS6qcwIBLVs8Vm5ZBnDYbW7ldni3LdmwAqrZAjVXQrloT0nunu6brW21tBzRXyZAyLR7L2oaF14cmusoXzndsadsakvsZyAYSkjQ52g57BW3VqbAHEMQnTtq5uYb4NOHN5xa1IvdecZCgSHNHzKPWYq1VsWZB7qvQgHXvoRAZD&limit=25&after=MzA0MjY5OTI5NzgwODIz"
   }
}

所以我想迭代这个对象。 我有以下代码正在运行。但我是Javascrip的新手,这样我正在做的是一种高度复杂的方式。一旦这种情况被召唤了很多次,我怎能做到这么简单呢?

for (var key in theData) {
   var obj = theData[key];
   for (var prop in obj) {
      var eventObj = obj[prop];
      for (var attribute in eventObj){
         if(eventObj.hasOwnProperty(attribute)){
            console.log(attribute + " = " + eventObj[attribute]);
         }
      }
   }
}

1 个答案:

答案 0 :(得分:5)

您可以使用Object.keys

Object.keys(httpResponse).forEach(function (key) {
    console.log(key + ' = ' + httpResponse.data[key]);
});

它更容易实现,也更易读。

对于您的代码,您可以使用以下内容:

function scan(obj, root) {
    root = root || '';
    Object.keys(obj).forEach(function (key) {
        if (typeof(obj[key]) === 'object') {
            scan(obj[key], root + key + '.');
        }
        else {
            console.log(root + key + ' = ' + obj[key]);
        }
    });
}

scan(httpResponse);

您可以a fiddle显示上述示例。

如果您需要支持IE< 9,您可能需要使用a polyfill