Javascript sort obj change id #

I am trying to sort my hash table menu alphabetically ... using this function:

function getSortedKeys(obj) { var keys = []; for(var key in obj) { keys.push(obj[key]); keys[keys.length-1]['key'] = key; } return keys.sort(function(a,b){ return a.name > b.name ? 1 : a.name < b.name ? -1 : 0; }); } 

This sorts the dropdown menu ... although it changes the original identifier # of my menu items, which twists some things on my site ... is it possible to keep the original identifier of each menu item and sort

sorry .. this is the hash code:

 var clientProjectsHash = {}; clientProjectsHash['1'] = {}; clientProjectsHash['1']['name'] = 'RONA'; clientProjectsHash['2'] = {}; clientProjectsHash['2']['name'] = 'CMS'; clientProjectsHash['3'] = {}; clientProjectsHash['3']['name'] = 'ALT'; 

and getSortedKeys is called:

 function getInitialClient() { clientProjectsHash = getSortedKeys(clientProjectsHash); for (clientKey in clientProjectsHash) { if(clientKey > 0) { return clientKey; } } } 
+4
source share
1 answer

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; } } } 
0
source

Source: https://habr.com/ru/post/1490326/


All Articles