Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

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 ], ... ]
}

Answer №1

As specified, objects do not have an inherent order of properties. Although the order is typically consistent in practice, it is not advisable to depend on it.

Reorganizing the properties each time you need to access the next or previous one is extremely inefficient. It is best to utilize an array to permanently store your sorted entries.

If the primary operations you intend to perform on your structure are next and previous, and there are numerous items involved, consider using a doubly-linked list for cost-effective operations.

For both efficient direct access and linked-list behavior, a compromise may be necessary. You could employ an array or Map for quick access, while also maintaining next and previous properties on all items for linked-list functionality. This approach may incur some overhead during structural changes, but can be acceptable if changes are infrequent.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

What is the best way to initiate a fresh AJAX request whenever the submit button is pressed?

Every time the submit button is clicked on my form, a modal appears and gets filled with JSON data from the application /addresschecker. If I receive an error message with a code return number of 2003, it indicates an issue with the addresses provided. Oth ...

Tips on emulating typing actions in an input field during a Jest test

I am working on a component that displays type-ahead suggestions as the user types in a text field. The suggestions are fetched from a server based on the input provided by the user. I want to test this functionality by simulating a scenario where the us ...

Updating a JavaScript global variable within a click event function: A quick guide

I am currently using Javascript and jQuery to retrieve the mouse coordinates of a click event for use in other Javascript functions. The issue I am facing is that global variables set within an event function do not update outside the function, unlike glob ...

After using driver.execute_script, the variable results in nil

Attempting to retrieve a lengthy string of URLs separated by commas is proving challenging. The code functions correctly in the console, but when running the script, the ruby variable urls_list remains nil. require 'rubygems' require 'selen ...

Guide on integrating signalr.js into webpack within Angular 2 environment

Every time I try to use SignalR, I encounter the following error message: $.hubConnection is not a function Error: jQuery was not found. Make sure that jQuery is included before the SignalR client JavaScript file. Checking with console shows "$" and ...

Expanding the boundary with Material-UI: Tips for stretching the margin

I am currently working on creating a navigation bar using Material UI, and the current layout can be seen in the image below. https://i.stack.imgur.com/AOy3v.png While following the template provided by MUI documentation, I encountered an issue with alig ...

Passing an array of selected values from Vue.js to a text area and adding them to the existing content

I'm facing a situation and I could really use some assistance. The image shows that there is a multiple select box on the left with numbers, and a text box on the right. My goal is to allow users to click on the house numbers in the select box and hav ...

Discovering the Power of Angular 5's Rxjs forkJoin Feature

Here is the code snippet in question: this.playerSearchService.getPlayerByPlayerTag(this.searchValue).flatMap(player => this.clanSearchService.getClanByClanTag(player.clan.tag).map(clan => { return Observable.forkJoin([Observable.of(player), ...

Variables in the $scope object in AngularJS

Within my $scope in angularJS, I am working with two types of variables. 1). $scope.name and $scope.title are linked to input boxes in the UI html code. 2). On the other hand, $scope.sum and $scope.difference are internally used within my JS code. I need ...

Identify the specific element using a designated data attribute

Having trouble figuring out how to select a specific element with a particular data attribute. In my situation, I want to target the a element with class="zoom-image" and data-order-item-id="<?=$order_item_id ?>". Here is the HTML/PHP code snippet ( ...

Can a JavaScript file be imported exclusively for a Vue component?

When attempting to utilize the table component in the vue-ant framework, I am facing an issue. I am only looking to import the table style, but when I try to import the table style using import 'ant-design-vue/lib/table/style/css', it affects all ...

Organize data in the store using @ngrx/data and @ngrx/entity, rather than within the component (subscriber)

When working with the ngrx/data library, I often find myself having to manipulate and format data from the store in various parts of my application. While I have utilized the filterFn function to retrieve only the relevant entities for my use case, I am st ...

Sending data to a parent component from a popup window in Angular Material using a button click while the window is still open

How can I retrieve data from an Angular Material Dialog Box and send it to the Parent component? I am able to access data after the dialog box is closed. However, I am wondering if there is a way to retrieve data while the dialog box is still open, especi ...

Create a dynamic effect by adding space between two texts on the page

const Button = () => { const options = ['test1', 'test2', 'test3']; return ( <div style={{ position: 'absolute', left: '8px', width: 'auto', flexDirection: 'row' ...

Having trouble with Angular 2 and Ionic2 mocks? Getting an error message that says "No provider

Currently in the process of creating a spec.ts file for my application. The challenge I'm facing is related to using the LoadingController from ionic-angular. In order to configure the module, it requires providing the LoadingController (due to its pr ...

AngularJS requires that JSON object property values be converted to strings in order to be displayed as actual templates

Each tab click accesses a json array containing unique templates such as ui-grid or c3 chart directive (c3.js). When a specific tab is clicked, the template in string format must be rendered into actual templates like ui-grid, c3-chart, etc. var sampleJs ...

What is the best way to arrange the elements of a dropdown list in reverse order?

I have the following code snippet used to retrieve data from a database and display it in a dropdown list: @{ int m = 1; foreach (var item in Model.MessagesList) { if (@item.receiverUserId == userId) { <li> <a class=&qu ...

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...

Error code 400 encountered during an HTTP POST request - issue stems from incorrect design of views and serializers

I keep encountering the following error: POST http://127.0.0.1:8000/api/creator_signup/ 400 (Bad Request) Every time I try to send data from my AngularJS application to my Django backend. When making a POST request, I used the following code (): fun ...