Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to.

My task involves retrieving a JSON array of objects with a service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MockDataService {

  private dataUrl = 'assets/data';

  constructor(private http: HttpClient) {}

  get(filename: string) {
    return this.http.get(`${this.dataUrl}/${filename}`);
  }

}

Using this service, we can input a filename of a JSON file and obtain an observable:

import { Component, OnInit } from '@angular/core';
import { MockDataService } from '../../shared/services/mock-data.service';
import { ObservableInput } from 'rxjs';

@Component({
  selector: 'app-iconography',
  templateUrl: './iconography.component.html'
})
export class IconographyComponent implements OnInit {
  pbiMini$ = this.mockdata.get('pbi-mini-names.json');

  constructor(private mockdata: MockDataService) {}
  ngOnInit() {}
}

However, the challenge lies in the need to sort this data based on one of the object keys, such as "name"

{
  "name": "Palette",
  "code": "pbi-palette",
  "char": ""
},
{
  "name": "Shopping tag",
  "code": "pbi-shopping-tag",
  "char": ""
},

I have researched but haven't found a solution. Previously, when dealing with JSON as a plain array rather than an observable, I successfully utilized

ngOnInit() {
  this.pbiMini.sort((a, b) => a.name.localeCompare(b.name));
}

Unfortunately, this approach doesn't work with the current observable. How should I go about it?

Update

In response to a suggestion, I attempted

ngOnInit() {
  this.pbiMiniSorted$ = this.pbiMini$.pipe(
    map(array => {
      return array.sort();
    })
  );
}

However, this fails to compile with the error: error TS2339: Property 'sort' does not exist on type 'Object'.

Answer №1

Utilize the map operator to transform the data within an Observable.

let numbers$ = of([5, 3, 8]);
let modifiedNumbers$ = numbers$.pipe(
  // The map function takes in an Array and outputs a modified Array
  map(numbers => {
    // Perform any necessary transformations on the Array here
    return numbers.reverse();
  }),
);

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

Troubleshooting: Issues with updating a text field in Vue test utils using Jest

Hello, I am new to Jest and unit testing. I have a question about how to set the value of a text input using Vue Test Utils. Here is the code for my custom text input component: <input v-model="local_value" @keyup.enter="submitTo ...

Rearranging data received from an Observable

TL;DR I am working on an Angular app where I need to shuffle an array of names retrieved from a network request and ensure that each group of 6 names selected is unique. However, I noticed duplicates in the selections. Here's a CodePen example using o ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

Javascript involved in the process of CSS Background-Images loading after HTML Images

I quickly put together a microsite that is located at . If your internet connection isn't fast or nothing is cached, you may notice that the background-images used for CSS image-text replacement are the last items to load (especially the h1#head with ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...

Converting DateTime objects into JSON format for use in AJAX calls

When utilizing my AJAX method, it returns a view model that is serialized as a data structure using JavaScriptSerializer().Serialize(). Among this data are several nullable DateTime? properties. I recently discovered that these dates appear in JavaScript ...

Using mat-select along with formControl to establish the default value

I'm struggling to assign a default value to my formControl, but it doesn't seem to be working as expected. select-hint-error-example.ts export class SelectHintErrorExample { animalControl = new FormControl('', [Validators.required]) ...

AngularJS dropdown menu for input selection binding

Hey there, I need some help with the code below: <input type="text" class="form-controlb" ng-model="item.name" id="name" placeholder="Enter Name" /> Also, I have a dropdown as shown here: <div class="col-sm-12" ng-model="query"& ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...

How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js. <li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." > Content </li> My goal is to apply a class to the li el ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

Ignoring the no-unused-vars rule from StandardJS even though variables are being used

Within my Typescript React project, I have declared the following: export type NavState = { mounted: boolean } I then proceeded to use this within a component like so: import { NavState } from '../../models/nav' class Nav extends React.Compon ...

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

Transferring parameters via URL - When passing single quotes, they are converted to &#39;

In my current ASP.NET project, we encounter an issue with passing parameters through the URL. Whenever a single quote is passed, the URL automatically changes all single quotes to %27 and the actual JavaScript value reads them as &#39; I need assistan ...

Oops! Looks like there was an error: $http is not defined

I'm facing a challenge with implementing $http in the AngularJS framework. I've gone through various other resources on this issue, but I can't seem to figure out what I'm doing incorrectly. Any assistance would be highly appreciated. T ...

What is the best way to conceal the previous arrow when on the first item, the next arrow when on the last item, and both arrows when there is only one item in an

Within this template file, I am aiming to incorporate the following functionality: hiding the previous arrow on the first item, hiding the next arrow on the last item, and hiding both arrows if there is only a single item. This implementation utilizes the ...

Removing unexpected keys during validation using Joi

Within my server-side JavaScript code, I am utilizing Joi for validating a JavaScript object. The schema being used is structured as follows: var schema = Joi.object().keys({ displayName: Joi.string().required(), email: Joi.string().email(), e ...

AngularJS ng-repeat to create a series of radio button options

This particular snippet of code generates two sets of radio buttons. The first set consists of individual radio buttons, while the second set is dynamically created using ng-repeat. Users can select any of the radio buttons by clicking on them directly or ...

Angular Material datetime picker with an option for transparent background

After upgrading my angular from version 15 to 16, I encountered a strange issue with the material date time picker. The GUI part of the picker appeared half transparent as shown in this image: https://i.sstatic.net/LC91N.png Has anyone else faced this ki ...