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?

5
  • 1
    The order of keys in an object is trivial but you could make an array of objects. Commented Jul 8, 2013 at 8:54
  • 2
    @elclanrs "trivial" ? Is that the right word ? Commented Jul 8, 2013 at 8:56
  • 2
    JavaScript does not have associative arrays. You are probably talking about object keys and their order is not guaranteed. Commented Jul 8, 2013 at 8:56
  • @dystroy: I mean it doesn't really matter, because you have named keys right? Commented Jul 8, 2013 at 8:57
  • So how do you suggest I go about this? I don't really wan to crate a loop in a loop. Commented Jul 8, 2013 at 9:09

1 Answer 1

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;  
};
Sign up to request clarification or add additional context in comments.

3 Comments

Note, that Object.keys(3rdPartyData) is not supported in EVERY browser. IE<9 doesn't have this.
Yes, but it can be easily added...
@Olegas: You mean "is not supported in every browser" I presume. Firefox and Chrome support it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.