The problem is that you are returning an array and expect it to be an object. These are different things in JavaScript. Nothing is "changing"; your "identifiers" (or "hashes") do not change.
Your clientProjectsHash starts as an object! Objects are unordered and may contain any string as a key. When you do getSortedKeys(clientProjectsHash); , an array is returned to you! Arrays are ordered and have numerical indices (keys) starting with 0.
clientProjectsHash = getSortedKeys(clientProjectsHash); for (clientKey in clientProjectsHash) { }
This overwrites the clientProjectsHash array. Then you are for..in above it (you should not use for..in for arrays, by the way).
The array returned from getSortedKeys looks like this:
[ { name: 'ALT', key: 3 }, { name: 'CMS', key: 2 }, { name: 'RONA', key: 1 } ]
So in your for..in , clientKey will be 0 , 1 and 2 . Array indices The key values do not change, you just read the wrong value.
Try this instead:
function getInitialClient() { var clientKeys = getSortedKeys(clientProjectsHash); for(var i = 0, len = clientKeys.length; i < len; i++){ var clientKey = clientKeys[i]; if(clientKey.key > 0){ return clientKey.key; } } }
source share