我有一些看起来像这样的物体。
foo = {
0 : {
'bar' : 'baz',
'qux' : 'quux',
'this' : { 'hello' : 'yes' } // this is the object I want to extract
}
1 : {
'bar' : 'baz',
'qux' : 'quux',
'this' : { 'hello' : 'yes' } // extract
}
2 : {
'bar' : 'baz',
'qux' : 'quux',
'this' : { 'hello' : 'yes' }, // extract
'that' : { 'hello' : 'no' } // extract
}
}
使用这样的 for 循环,我可以循环遍历每个对象:
for(var i in foo){
...
}
问题是我只想从每个对象的第三个且比 ('this') 更大的子对象中提取数据。
最佳答案
ECMAscript 中的对象键没有指定的顺序。如果您仍然对键名进行了索引,那么您确实应该使用 Javascript 数组。
如果您需要一个普通的Object,您可能需要将Object.keys()
与Array.prototype.forEach
一起使用,并且.sort()
,如
Object.keys( foo ).sort().forEach(function( i ) {
});
<小时/>
如果你不能依赖 ES5,你别无选择,只能手动完成这项工作。
var keys = [ ];
for(var key in foo) {
if( foo.hasOwnProperty( key ) ) {
keys.push( key );
}
}
keys.sort();
for(var i = 0, len = keys.length; i < len; i++) {
}
<小时/>
但是,您确实应该首先使用数组,这样您就可以跳过脏活。
关于Javascript - 对象,for 循环从 2 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15806989/