0

I have an associative array (object) in wich I store data loaded from a 3rd party.

// 3rdPartyData is also an associative array
for(var key in 3rdPartyData) {
  cookie[key] = 3rdPartyData[key];
}

My object gets stored into a cookie at the end and gets loaded form a cookie before (or created {} if no cookie exists).

Each page view the data from the 3rd party gets added or updated in my cookie array.

Question: If I wore to look the cookie, would the loop always get each key in the order they wore added to it or would the order be changed?

If so can anyone provide an idea on how to manage something like this?

transilvlad
  • 12,220
  • 12
  • 41
  • 77

1 Answers1

0

The order of keys in for(var key in some_object) can be any, and certainly is not always sorted, but you can force the order to be the one you want:

for(var key in Object.keys(3rdPartyData).sort(keysSorter) {
    cookie[key] = 3rdPartyData[key];
}

keysSorter = function(a, b) {
    if (a === b) { // Should not actually be the case when sorting object keys
        return 0; 
    }
    // Compare a and b somehow and return 1 or -1 accordingly
    return a < b ? 1 : -1;
}

And to make sure Object.keys() will work:

Object.keys = Object.keys || function(o) {  
    var result = [];  
    for(var name in o) {  
        if (o.hasOwnProperty(name))  
            result.push(name);  
        }  
    return result;  
};
mishik
  • 9,595
  • 9
  • 39
  • 62