Arrange items within an array using keys that can change dynamically

I'm currently working on sorting an array of dynamic key / value pairs (Objects) based on a specific property within the object. Can anyone provide me with an example of how to accomplish this? I will attempt to replicate a similar structure for my issue.

Here is an example of the Order Class:

export class Order {
  id: number; 
  productRank: number; 
  productId: number; 
  productName: string;
}

In my component, there is an observable array called storeOrders containing orders:

storeOrders$: Observable<Array<Order>>;

The keys in the orders array are dynamically generated and stored as key/value pairs with the key being represented by the order object.

For example, the orders object looks something like this:

 let orders = {
12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt'},
23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne'},
67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }       
 }

When subscribing to this data, how can I iterate over the storeOrders array and sort the items based on the productRank property? I've been struggling to get this right and would appreciate any guidance on how to iterate over dynamic keys in an array and perform a sort based on a property within the value object. Thank you for your help!

Answer №1

Here is an example of how your orders should be structured:

orders = {
    12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt' },
    23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne' },
    67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }
  };

To access the values, you can use Object.values(orders)

I personally prefer using the sortBy function from lodash library for sorting, which can be done like this:

console.log(sortBy(Object.values(orders),['productRank']));

Check out Stackblitz for more details.

Answer №2

If you want to arrange a dynamic array of keys and values in a specific order, here's how you can do it:

Take a look at this example array:

arr = [
{de : 'germany'},
{fr : 'france'},
{uk : 'united kingdom'},
{tn : 'tunisia'}
]

arr.sort((a, b) => {

      const a_key = Object.keys(a);
      const a_value = a[a_key];
      const b_key = Object.keys(b);
      const b_value = b[b_key];

      if (a_value == b_value) return 0;
      return a_value > b_value ? 1 : -1;
    });

That's all there is to it!

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

Typescript errors in console not being displayed by swc-loader

I have decided to make the switch from ts-loader to swc-loader based on the guidance provided in this article. However, after completing the migration, I am encountering an issue where basic Typescript errors are not being displayed in the console. For ins ...

Personalize the highcharts tooltip to display date and time

I'm working on a new project where I need to display a graph like the one you can see here: http://jsfiddle.net/Kc23N/ One issue I am facing is that when clicking on a point (tooltip), I want to show a date in a readable format rather than just the v ...

Which is the best place to initialize variables in Angular: Constructor, Declaration, or ngOnInit, including observables?

Here is an Angular component code snippet: export class ListComponent implements OnInit { showComments: boolean = false; posts$: Observable<PostModel[]>; constructor(private postService: PostService) { } ngOnInit() { this.posts$ = t ...

Tips for comparing two typed objects using interfaces in React?

I am currently working in TypeScript and facing a challenge where I need to obtain the delta (key/value) of the modified attributes between two objects. Both objects are created using the same interface. export interface ITestObj { att1: string; att ...

Employing ng-style for establishing background when the value does not align

Greetings all! I am using ng-repeat to create a list of items within a ul element. Within the json data, there is a specific value that I want to highlight if it does not match a predefined string. Here's what I have so far: ng-style="{'backgro ...

Monitor changes in input display within ngIf statements

Within my code, I am utilizing an input element within a conditional statement of *ngIf: <div *ngIf='display'> <input number="number" /> </div> My goal is to be able to detect the visibility state of the input element insi ...

Unsubscribe option in the AWS Software Development Kit for Node.js

Is there a way for me to include a List-Unsubscribe : <mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdddedffcdfd8da92dfd3d1">[email protected]</a>> header in my outgoing email message while using A ...

Is it possible to insert items into Vue component data? I'm interested in creating a table following JavaScript filtering and manipulation

I'm working on a website that will have multiple pages, each containing tables. To streamline this process, I wanted to create a table component. However, I haven't added any data to the tables yet because I need to manipulate it using JavaScript ...

Is it possible to use export default Enum in TypeScript?

I am facing an issue with exporting an enum object as default at the top level in my code. Here is what I tried: export default enum Hashes{ FOO = 'foo', BAR = 'bar', } However, this resulted in an error message: Module parse failed ...

Saving numeric values from a text document into a two-dimensional grid

I am currently working on a program that reads data from an array file arranged by rows and columns, and then checks if five consecutive characters are the same horizontally, vertically, or diagonally in order to color them differently in my GUI. However, ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

Displaying information based on selection in AngularJSIn this tutorial

I am a beginner in Angularjs and currently working on developing a website. One of the tasks I have is to create a combo box that, when an option is selected, calls a method to load values into a Scope variable and update it. Below is the code I have so fa ...

Send information from a web page's elements to PHP with the help of AJAX

My goal is to integrate AJAX, HTML, and PHP to create a seamless user experience. I am currently facing difficulty in passing variables to the PHP form. The method I've employed seems a bit complex, especially since this is my first attempt at using A ...

Is it appropriate to delete the comma in the Ghost Handlebars Template?

While navigating through the tags, I unexpectedly encountered a comma. This could potentially have an unwanted impact. I attempted to remove the comma, but is there a specific method to eliminate it completely? I referred to the Ghost blog Document for gui ...

Problems with Vuex getter reactivity when used in conjunction with Vue router

I've encountered an issue with my Vuex getter that fetches data for the current route and displays it in a Vuetify v-data-table. Everything works perfectly fine when the component is initially created. However, when I add a new entry to the data array ...

Instantiate an object of the ng.IQService type without using injection

Is it possible to define a local variable in the controller of type ng.IQService ( private _q: ng.IQService;) without requiring injection? My technology stack includes typescript and angular. The reason for this requirement is due to existing legacy code ...

Angular Elements: integrate the Angular core just one time

Angular Elements refer to Angular components that are packaged as custom elements. Each Angular Element ships with the Angular core. If I were to include 5 Angular Element components on a standard HTML page, the page would download the Angular core 5 times ...

Vue.js build fails with JSON errors rendering a blank page

As I was building my first project to learn more about vue.js, I encountered an issue when using npm run build. It resulted in blank pages with errors related to JSON. However, when I used the typical npm run serve command, the page looked great and worked ...

Changing the hover background color and text color of Material UI Button

I recently developed a custom Appbar component using React.js that includes 3 buttons. I'm looking to enhance the user experience by changing the color scheme when users hover over these buttons. Currently, the background color is set to #3c52b2 and t ...