如何循环访问对象中的编号属性

How To Iterate Through Numbered Properties in Object?

本文关键字:对象 编号 属性 访问 何循环 循环      更新时间:2023-09-26

我有一个大对象,里面有 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....

在纯 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
   }
}

使用下划线,您可以像马克的答案一样写它,但要用类似的if(!isNaN(prop))_.isNaN检查

使用下划线。

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

试试这个:

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)