[英]How To Iterate Through Numbered Properties in Object?
我有一個超過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....
使用下划線。
_.each(yourObject, function (item, index) {
console.log(item.emails);
console.log(item.title);
// etc...
});
在純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
檢查
嘗試這個:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.