Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through a javascript object in order [duplicate]

Tags:

javascript

Here's the situation. I have a JavaScript object and I need to iterate through it, but the order is very important to maintain. I know that JavaScript object is supposed to be unordered, but I was hoping there was some JavaScript equivalent to the following: http://docs.python.org/2/library/collections.html#collections.OrderedDict

This is the original ordering

{
  082013: {'A': 1, 'B', 3}
  092013: {'A': 2, 'B', 4}
  102013: {'A': 8, 'B', 2}
  112013: {'A': 92, 'B', 67}
  122013: {'A': 64, 'B', 32}
}

Then I iterate through it:

aArray = [];
bArray = [];
$.each(data, function(key, value) {
   aArray.push(value.A);
   bArray.push(value.B);
});

the result (on chrome in particular) seems to render more like this:

aArray = [8, 92, 64, 1, 2];
bArray = [2, 67, 32, 3, 4];

This implies that it does not iterate in order, or goes through it in the order of smallest to largest (102013, 112013, 122013, 092013, 082013)

So how could I iterate this object in order, if I can at all?

like image 326
corvid Avatar asked Dec 17 '13 17:12

corvid


People also ask

Can you forEach an object?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object. keys() , Object. values() , or Object.

Can we use for loop to iterate an object in JavaScript?

Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes.

Does for of iterate in order?

Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.


1 Answers

Off the top of my head, the only way to do this is get the keys (using Object.keys(myObj)), then sort them (using Array.sort) and go through it that way. The keys are unordered in the actual object.

So it's something like:

    var keys = Object.keys(myObj);
    keys.sort();
    for(var i=0; i<keys.length; ++i){
        //do something with myObj[keys[i]]
    }
like image 111
willy Avatar answered Oct 26 '22 20:10

willy