0

I have objects looking like this.

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

with a for loop like this I get to loop through every object:

for(var i in foo){
  ...
}

The problem is that I only want to pull the data from the third and greater child object than ('this') from each object.

11
  • 4
    Object properties are not ordered. Use arrays instead. Commented Apr 4, 2013 at 9:12
  • Objects are unordered. There isn't really a concept of a "first" or "second" key-value pair. Are you just trying to get all keys that happen to have values that are objects? Commented Apr 4, 2013 at 9:13
  • If I always know that they will come in this order? Commented Apr 4, 2013 at 9:13
  • Use this format and regular for loop: foo = [{},{},{}] Commented Apr 4, 2013 at 9:14
  • @Philip: There is no order. That's just the way they're being displayed. Commented Apr 4, 2013 at 9:14

1 Answer 1

2

There is no specified order for object keys in ECMAscript. You really should use an Javascript Array if you have indexed key names nonetheless.

If you need to have a plain Object, you might want to use Object.keys() alongside Array.prototype.forEach and .sort(), like

Object.keys( foo ).sort().forEach(function( i ) {
});

If you can't rely on ES5, you have no choice but to do the work manually.

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++) {
}

However, you really should just use an Array in the first place, so you can skip the dirty work.

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I can't use Object.keys with IE.
Thanks for the solution, I think that I will make an array of it instead.! =)
Wouldn't var cnt = 1,cur;while (cur = foo[++cnt]) {...} work too, though it still doesn't make much sense using an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.