Sorting a typescript model using the .sort() method

I am working with the following code snippet:

export interface Model{
  fields: FieldMap;
}
export interface FieldMap {  [key: string]: Field;}
export interface Field { name: string; value?: string;   }

My question is, how can I sort the field model by key?

I attempted something like this, but encountered error TS2349:

Cannot invoke an expression whose type lacks a call signature.

.fields.sort((a: any, b: any) => { if (a.key < b.key ){ return -1; }else if(a.key > b.key){ return 1; }else{ return 0; } });

Answer №1

It seems like you're attempting to arrange the FieldMap object based on key values.
For reference, here is a helpful link

You may give it a try by following this method:

var data = {
    fields: {
        "4": { name: 'name4', value: '4' },
        "1": { name: 'name1', value: '1' },
        "3": { name: 'name3', value: '3' },
        "2" : { name: 'name2', value: '2' }
    },
};

Object.keys(data.fields).sort((a: any, b: any) =>
{ if (a.key < b.key) { return -1; } else if (a.key > b.key) { return 1; } else { return 0; } });

alert(JSON.stringify(data.fields));

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

Obtain numerous variables from a .ts file and bring them into a separate file within Angular 4

I am interested in creating a config.ts file to store the global values of my app. I have been able to use it in this way: module.exports.key = "My key"; However, I need to export multiple values, around 20-30. Is there a more efficient way to do this wi ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Assign a value to a FormControl in Angular 6

I have 60 properties linked to 60 controls through the mat-tab in a form. When it comes to editing mode, I need to assign values to all the controls. One approach is as follows: this.form.controls['dept'].setValue(selected.id); This involves l ...

Application suddenly crashes due to a severe issue: FATAL EXCEPTION: java.lang.RuntimeException, preventing the activity from starting

I recently updated my Ionic, Angular, and Capacitor application to the latest versions - Ionic 7, Angular 16, and Capacitor 5. After the update, I noticed that on Android, the app works fine when installed for the first time. However, upon restarting the a ...

I have been attempting to incorporate icons from fluent ui northstar into the fluent ui dropdown component, but unfortunately, there is a lack of adequate documentation

I attempted to use renderItem to include a divider and Icon in a Fluent UI dropdown menu, but the icons are not visible. Even the default value does not display the icons, and the dropdown menu does not appear after clicking. import * as React from " ...

Tips for looping through a Set in TypeScript

What is the best way to loop through a set in TypeScript? Using for..of does not seem to work properly: 'Set<string>' is neither an array nor a string type Using .forEach is not ideal since it obscures the context of this. I would rather ...

Executing a Typescript function in an MVC5 cshtml file, optimized with webpack bundling

Brand new to webpack, and I'm facing obstacles in merging MVC components with webpack AND typescript. Take a look at my code combinations below: webpack.config.js: var wbConfigEntries = { "jqkendoMain": [ paths.appjs + "main.ts" ] }; ...

A guide for implementing fast-json-patch in your Angular 2 projects

Looking to incorporate the "fast-json-patch" library into my Angular 2 project. This library can be found at https://github.com/Starcounter-Jack/JSON-Patch. I attempted to include the following code: 'fast-json-patch': 'vendor/fast-json-pa ...

Typescript may fall short in ensuring type safety for a basic reducer

I have been working on a simple reducer that uses an object to accumulate values, aiming to maximize TS inference. However, I am facing difficulties in achieving proper type safety with TypeScript. The issue arises when the empty object does not contain an ...

Finding the data type of a collection of functions stored in an associative array

I am seeking assistance in creating a function where the caller must provide an associative array of functions. The function should return a new associative array with the same keys and return types, but each function will take a different argument compare ...

Detecting a page refresh in Angular 16: Tips and tricks

My Angular 12 code is functioning properly, but when I migrated it to Angular 16, it stopped working. Can you please suggest the necessary changes to make it work in Angular 16? Here is the code snippet: this._router.events .pipe(filter((rs): rs ...

Preventing angular mat-menu from closing when clicking outside of it: simple solutions

When implementing MatMenu as a popup for guiding new users on my web app, I prefer not to close it when the user clicks outside of it. I've successfully used $event.stopPropagation() to prevent closure when clicking a button within it. Now, I'm ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Dealing with Errors in Angular 8: Best Practices for Handling Response Errors

When an error is thrown from the WEB API, I do not receive any response and the debugger does not hit. However, in case of success, I do get a response and the debugger hits. All I want is to receive an error response and have the debugger hit every time, ...

Styling: petite vibrant square positioned in the corner of a large container

Can you please take a look at the screenshot from the demo app: box over box image I am trying to create a colorful small square box that will appear in the top left corner, on top of the larger parent square box (including all the contents inside the whi ...

Values separated by a comma in MySQL

I am currently facing an issue with my SQL and PHP code. I have a statement that retrieves data from the services table along with its associated tables: $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the ta ...

Rxjs error: The 'pipe' property is not found on the 'UnaryFunction<Observable<{}>, Observable<string | {}>>' type

Currently working on implementing ngbTypeAhead and encountering problems with RxJS version 5.5.5. The example I am referencing is from version 6 of rxjs. "rxjs": "^5.5.2" and angular "^5.0.1", "typescript": "~2.6.1", While trying to apply typeahead on f ...

Trouble with Angular: mat-sidenav not responding to autosize or mode changes when resized

Currently, I am working on integrating the mat-sidenav into a project. Most of the functionality is working well, but there is one particular issue that arises. When running the app locally in a browser and resizing the window tab multiple times, it opens ...

Determine the output type of a function in Typescript using an input value specified by an enum

I am currently saving settings to local storage and want to be able to input responses when retrieving (and possibly inserting) values from/to the storage. After researching, it seems that using function overloading is the best approach. Here is what I ha ...

Preventing page reload when altering parameters in Angular 9

I have recently utilized Angular9 along with PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy}, The issue I am facing is: Whenever I use form.submit() to send data to the backend, the backend then redirects back to the c ...