如何通过对象中的编号属性进行迭代?

时间:2013-11-11 23:51:47

标签: javascript node.js express

我有一个包含超过700个属性的大型Object。我如何遍历每个编号的属性?

{ '0': 
   { emails: 
      { categorized: [Object],
        all: [Object],
        primary: 'support@wish.com' },
     id: '290cb70ea0f',
     updated: '2011-09-16T05:55:12.136Z' },
  '1': 
   { emails: 
      { categorized: [Object],
        all: [Object],
        primary: 'VJONO@csnfo.com' },
     id: '753ac508e1a00e',
     updated: '2012-07-12T22:23:11.196Z' },
  '2': 
   { title: 'Bryan Weston',
     phone_numbers: { categorized: [Object], all: [Object], primary: '' },
     id: 'b4c0268d92825e',
     updated: '2010-10-13T08:00:32.834Z' },
    // It goes on....

3 个答案:

答案 0 :(得分:2)

使用下划线。

_.each(yourObject, function (item, index) {
   console.log(item.emails);
   console.log(item.title);
   // etc...
});

答案 1 :(得分:2)

在纯JavaScript中,它会像这样

var data = { /*stuff*/ };
var item;
for (var prop in data) {
   //hasOwn is probably not needed
   if( /*data.hasOwnProperty(prop) &&*/ !isNaN(prop) ) {  //only do stuff if the property is a number
       item = data[prop];
       //work
   }
}

使用Underscore,您可以按照Mark的回答编写,但使用类似的if(!isNaN(prop))_.isNaN支票

答案 2 :(得分:0)

试试这个:

var objectKeys = Object.keys(yourObject).map(Number);
objectKeys.sort();
for(var i=0;i < objectKeys.length; i++) {
    key = objectKeys[i];
    element = yourObject[key];
    //do magic here
}

如果您不关心处理顺序,可以使用for(key in youObject)