1

我有一个包含 700 多个属性的大型对象,所有属性都已编号。如何遍历每个编号的属性?

{ '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....
4

3 回答 3

2

使用下划线。

_.each(yourObject, function (item, index) {
   console.log(item.emails);
   console.log(item.title);
   // etc...
});
于 2013-11-11T23:54:33.057 回答
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
   }
}

使用下划线,您可以像 Mark's answer 一样编写它,但使用类似的if(!isNaN(prop))_.isNaN检查

于 2013-11-11T23:57:54.257 回答
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)

于 2013-11-12T00:12:28.130 回答