I am new to Angular and currently working on a Angular 5 application. I have a requirement to get the next or previous item from a dictionary(model) for next and previous navigation to get the route. I looked into multiple articles and came up with the following method. Let me know whether any other efficient and reliable way to do this. I need to also make sure its sorted by value to make sure it retains the same order between server(api) and client. This will be an important method for our application navigation so I want to make sure there is no browser compatibility issues, no drawbacks and its reliable. Worst case I can go with regular switch case statement, it will be ugly with multiple conditions but will be OK. Let me know your thoughts. Thanks 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 ], ... ]
}