How to filter specific attributes from a JSON object and transform them into an observable with RxJS

Consider the JSON data that is being received:

{
    "events": [...
    ],
    "total": 12341,
    "students": [
        {
            "id": 1,
            "first_name": "John",
            "last_name": "Apple"
        },
        {
            "id": 2,
            "first_name": "Bob",
            "last_name": "Banana"
        },
        {
            "id": 3,
            "first_name": "Charles",
            "last_name": "Carrot"
        }
    ]
}

The goal is to transform this data into a specific format and return it as an observable:

[
    {
        "first_name": "John",
        "last_name": "Apple"
    },
    {
        "first_name": "Bob",
        "last_name": "Banana"
    },
    {
        "first_name": "Charles",
        "last_name": "Carrot"
    }
]

An attempt was made to achieve this transformation, but it resulted in returning undefined:

getStudentsName(): Observable<any> {
    const requestUrl = this.rootURL + `students/`;
    let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
    return studentsInfo.pipe(map(students => {students.first_name, students.last_name}));
  }

The subscription to the observable also returns undefined:

this.getStudentsInfoService.getStudentsName()
      .subscribe((result) => console.log('here', result));

Answer №1

It seems like the issue is that you are treating an array of students as an object. To fix this, you'll need to use a nested map function: one for rxjs and another for the student array

return studentsInfo.pipe(
  map(studentsArray => studentsArray.map(student => ({
    first_name: student.first_name,
    last_name: student.last_name
  }))),
);

PS.: If you had used types instead of any, you would have caught this mistake earlier. This was not noticed by you or other responders because of the lack of proper typing.

Answer №2

Seems like there's an issue locating students. Here is a possible solution:

return studentsInfo.pipe(map(s => { return {
  first_name: s.first_name,
  last_name: s.last_name,
}}));

Answer №3

Check out this concise code snippet.

const data = {
    "total": 12341,
    "employees": [
        {
            "id": 1,
            "first_name": "Alice",
            "last_name": "Apple"
        },
        {
            "id": 2,
            "first_name": "Bob",
            "last_name": "Banana"
        },
        {
            "id": 3,
            "first_name": "Charlie",
            "last_name": "Carrot"
        }
    ]
}

let newEmployees: any[] = [];
data.employees.forEach(person => newEmployees.push(
    {
        "first_name": person.first_name,
        "last_name": person.last_name
    }))

console.log(newEmployees)


    [LOG]: [{ "first_name": "Alice", "last_name": "Apple" }, 
{ "first_name": "Bob", "last_name": "Banana" }, { "first_name": "Charlie", "last_name": "Carrot" }] 

You can loop through employees using a forEach method and then construct a new JSON object to add to your array.

this.http.get<any>(requestUrl).pipe(map(data => data.employees.foreach(person => newEmployees.push({
...}));

Answer №4

The Issue

There is an issue with how the observable is being returned.

Let's analyze the code snippet

let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));

In the above code, studentsInfo will have a type of Observable<any>

The next line is shown below

return studentsInfo.pipe(
  map(students => {
    students.first_name, students.last_name
  }
));

Now, take a look at the section below

{
  students.first_name, students.last_name
}

This part does not have a return statement, resulting in JavaScript returning undefined by default!

Resolution

To utilize an arrow function without a return statement, enclose {} within () as shown below

students => ({ })

The corrected version is as follows

getStudentsName(): Observable<any> {
  return this.http.get<any[]>(`${this.routeURL}/students`).pipe(
    map(o => o.students));
  }

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

What potential issues should I be aware of when I install new node packages?

I encountered an error message when trying to install a Node Package. Running npm install shows that everything is up to date. https://i.stack.imgur.com/d78hf.png ...

What is the best way to check the value of a Reference type in a CDK stack

I have successfully created resources using the aws cdk library. I am now facing an issue with testing a stack that contains multiple resources. When testing a single resource, everything works fine, but I'm unsure how to test a stack with multiple re ...

The module 'atptest' could not be located or its corresponding type declarations are missing. Error code: ts(2307)

After creating an angular library using angular cli, I encountered an issue when trying to use it in any angular application after publishing it to npm. The published library installs successfully with the command: npm i atptest This is how I attempted t ...

Issue with Angular modal popup not repositioning upon clicking elsewhere on the page

I have encountered an issue with modal popups on my website. Specifically, I have approximately 100 table elements and when I try to edit the element #100, the modal popup appears at the bottom of the page. However, if I scroll back up and click on eleme ...

Lazy Loading Angular Components from a Separate Directory Beyond the App Folder

Having issues with lazy loading a module in my Angular project. Here is the current directory structure and code: I'm attempting to Lazy Load this module "tsdmns-modules/loader-module/tsdmns-loader-module.module" from "app/app-routing.module" an ...

Exploring the Integration of MariaDB JSON Features with Laravel Framework

As I attempt to establish a JSON database within XAMP, utilizing phpMyAdmin reveals that I am using MariaDB. However, in my xamp-control panel v3.2.2, it indicates that MySQL is running on port 3306. My endeavor involves Laravel 5.4 framework for the datab ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

How to eliminate escape characters in Jquery Post requests

I've come across several questions similar to mine, but I haven't found a satisfactory answer yet. My issue is as follows: I'm trying to convert a JQuery object into a Json String and then send this string to a PHP webpage. The sending part ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

How do I design a reactive form in Angular 8 that dynamically selects another dropdown option based on the selection of one dropdown?

I am a beginner in Angular and currently working on creating a reactive form. I want to have a functionality where selecting one value in a dropdown menu will automatically populate another dropdown menu with relevant data. Here is the object structure tha ...

Can Firestore be debugged effectively?

In developing my application, I've been utilizing Angular and Firestore. However, I've encountered a challenge when it comes to ensuring the security of my app, as most CRUD tutorials I come across do not address the specific rules needed for Fir ...

Angular: Extracting the default value of a FormControl within a Child Component

Is there a way to retrieve the initial value set in a FormControl for a custom component within its ngOnInit method? Suppose you have created a form control like this: testControl = new FormControl("abc123"); And then linked it to your custom component ...

Progress Bar for Uploading Files to AWS S3 using Angular 6 and Node.js

Seeking advice on how to implement a progress bar for file uploads using Angular 6 on the frontend and NodeJs on the backend, specifically to an AWS S3 bucket. Any suggestions on how to retrieve the progress of the upload (or the bytes already uploaded) ...

Tips for adding or updating query parameters in Angular2

When navigating and updating settings in my app, I am utilizing query parameters that I need to retain and update. Adding a parameter is simple using the following method. onNavigate() { this.router.navigate(['reports'], {queryParams: {'rep ...

Guide to creating a setter for an array property in Angular 2 (Typescript) that will be filled by the view

Question: private _secretQuestions: {question: number, answer: string}[]; Within my HTML, I have three select boxes representing questions, each with a corresponding input box for answers. My goal is to map the selected questions and input values to the ...

Transferring a JSON object to a PHP script

I am attempting to send a JSON object with a structure like this: {"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]} Just to note: The sizeTypes array contains a total of approximately 58 items. Upon clicking the submit ...

I am encountering an issue where I am only receiving "true" instead of the expected JSON format {"result":true} in my ASP

I am currently working on a project using asp.net web api to create a service that can be utilized by Android. JSON is necessary for parsing the data. However, I am facing an issue with the login method. All other methods are functioning properly, but wit ...

Receiving a response of success or failure when using android.SmsManager.sendTextMessage() in a NativeScript/Android application

I have a question regarding sending an SMS from my NativeScript mobile application. Below is the code I am using: sendSms(numbers, body) { let sms = android.telephony.SmsManager.getDefault(); sms.sendTextMessage(numbers, null, body, null, ...

Fetching values from JSON object using Key in Angular

Here is the code snippet for the markup and component in question: new.component.html <a routerLink="{{sub.name}}" routerLinkActive="active">{{sub.name}}</a> old.component.ts data; this.route.params.subscribe((params:any) => {console.lo ...

Getting a value from a JSON field in MySQL

I am facing a challenge with extracting form data from a column stored in a JSON string format. After searching online for solutions, I found that many recommended using regex to extract the desired value. How can I effectively apply regex to retrieve th ...