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

Unable to execute AJAX POST request

https://i.stack.imgur.com/JqG7c.pngI have a JSON dataset like the one below: [ { "Password": "tedd", "Username": "john", "status": true } ] I need to consume this data using a POST method <label for="Username">Username:</label& ...

Dealing with race conditions in Angular 2 nested resolvers and managing them effectively using RX

Back with an intriguing predicament! Currently, I am in the process of developing an angular2 application using RXjs observable data stores to supply data to my app. Upon launch, if a user is logged in, the app resolvers fetch the relevant user data and po ...

Unable to display and conceal div elements

<ol class="novice"> <li> <p class="glava">HTML</p> <div class="vsebina"> <p>Hyper Text Markup Language (slovensko jezik za označevanje nadbesedila...</p> </div> </li> <li> ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

Issue with toggling options in q-option-group (Vue3/Quasar) when using @update:model-value

I'm a newcomer to the world of Quasar Framework and Vue.js. I recently tried implementing the q-option-group component in my simple application but encountered an issue where the model-value and @update:model-value did not toggle between options as ex ...

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

Saving a group of selected checkboxes as an array in Ionic: a step-by-step guide

I am working on a simple form with checkboxes and I need to send only the checked boxes to TypeScript. However, when I attempt to save the data by clicking the save button, I encounter an error message {test: undefined} Below is the form layout: <ion-c ...

Utilize jQuery to dynamically load and assign unique ids to elements within an array

I am seeking assistance with dynamically assigning unique IDs to elements in an array using JavaScript and jQuery. I am new to these languages and need some guidance. function assignIds() { var elementIds = ['name', 'lname', ' ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Angular TSLint: Proceed to the following stage despite any encountered errors

I'm facing issues with TSLint in my Azure Devops Build Pipeline. Despite encountering lint errors, I need the build pipeline to proceed to the next step. How can I achieve this? Command Line: - script: | npm run lint > tsLintReport.txt ...

Managing Emails with Vue and Firestore

I am facing an issue with updating the 'email' field. Whenever I try to change the email address, it gets updated correctly. However, when I attempt to log in again, the new email address does not work; only the old one seems to be functional. Ho ...

How to Retrieve Input Field Value Using Cypress Custom Command

Is there a way to retrieve the value of an input[text] element within a custom command? Cypress.Commands.add('extendValue', { prevSubject: 'element' }, (subject: JQuery<HTMLElement>, extension: string): any => { const r ...

(React Native - Expo) The hook array fails to include the most recently selected object

When I attempt to add objects to a hook within a component, it seems to be functioning correctly. However, there is an issue where the last selected object is consistently missing from the updated hook array. This behavior also occurs when removing an obje ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...