I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solution. Please let me know if there is a more efficient and reliable approach. It is crucial that the items are sorted by value to maintain consistency between the server (api) and client. This method will play a key role in our application's navigation, so ensuring browser compatibility, eliminating drawbacks, and reliability are important. As a fallback option, I can resort to using a regular switch-case statement, although it may not be ideal due to its complexity with multiple conditions. I would appreciate hearing your thoughts on this matter. Thank you in advance.
var dict = {
"name3": 12,
"name1": 5,
"name2": 8
};
var items = sortProperties(dict);
//console.log(items);
var getItem = function(key, i) {
var index = 0;
var stop = true;
for (var j = 0; j < items.length; j++) {
if (items[j][0] == key) {
index = j;
break;// Found it
}
}
console.log(index);
if((index + i) > -1 && (index+i) <items.length)
{
return items[index+i][0];
}
else
{
return 'empty';
}
}
console.log(getItem("name2",-1));
console.log(getItem("name2",+1));
function sortProperties(obj)
{
// convert object into array
var sortable=[];
for(var key in obj)
if(obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]
// sort items by value
sortable.sort(function(a, b)
{
return a[1]-b[1]; // compare numbers
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}