Guide to retrieving specific attributes from an object within an array of objects using Angular Typescript

As an example, if we consider a sample JSON data retrieved from the JSONPlaceholder website at https://jsonplaceholder.typicode.com/users.

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3e0daddd0d6c1d6f3d2c3c1daf96dd4d8d7">[email protected]</a>",
    ... (JSON data continues)
 

From this array of objects, my goal is to extract an array of objects containing only "username" and "name" as demonstrated:

[
 {"name": "Leanne Graham", 
   "username": "Bret"},
 {    "name": "Ervin Howell",
     "username": "Antonette"
}
]

For accessing the JSON data, I am utilizing HttpClient. Below is the code snippet from app.component.ts:

interface user {
      username : String,
    name : String
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  users : Observable<user>
  constructor(private _http : HttpClient){}
  name = 'Angular ' + VERSION.major;
  ngOnInit() {
   this.users = this._http.get('https://jsonplaceholder.typicode.com/users')

To display the users array in the app.component.html with the async pipe, I am employing the following approach:

<div *ngFor = "let user of users | async" >
 {{user.Username}}
 {{user.name}}
</div>

I've experimented with creating a type interface for the entire json object and then filtering it using the map operator, but this method becomes cumbersome for large JSON datasets. If you have any alternative solutions, your input would be greatly appreciated. Thank you in advance.

Answer №1

Utilizing the map operator is the optimal approach. While you are seeking a solution with better than O(n) complexity, it is inevitable that you will need to traverse the entire array of objects in one way or another, resulting in a minimum linear complexity. One option is to use a traditional for loop to iterate through the data and then push to a new array, but this may introduce additional overhead time.

A general guideline is that when performing modifications on data stored in an array, the map method is preferred.

this.users = this._http.get('https://jsonplaceholder.typicode.com/users').pipe(
    map(users => users.map(user => ({ name: user.name, username: user.username })))
);

Answer №2

Below is an example code demonstrating how to alter an existing array of objects using the map operator.

Assuming that your interface is named user:

interface user {
  username: String,
  name: String
}

let updatedArray: Array<user> = this.users.map(user => {
  return <user>{
    username: item.username,
    name: item.name
  }
})

Feel free to review the updatedArray and inform me if it meets your requirements. I appreciate any feedback you can provide. Thank you!

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

How can we retrieve URL parameters with the help of ActivatedRoute in Angular?

My current route configuration is as follows: { path: "events", component: SkeletonComponent, children: [ { path: ':id', component: ViewEventComponent } ] } The constructor of my component looks ...

Improving Angular component performance with a multitude of subcomponents

Some time back, I created a grid component for an Angular application. Each Grid consists of rows represented by Row components, and each Row contains cells that are also components called Cell. These cells can hold various "objects" which are essentially ...

The Angular Serviceworker does not store the index.html file in its cache

When my app goes offline, it doesn't work properly due to the angular serviceworker failing to cache my index.html file (although it does cache other files like js, css, manifest, and ico). The issue only occurs when the outputPath is within my git/nx ...

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

Having trouble executing a method from a template in Angular 5?

Angular has a useful capability that almost every developer has utilized at some point: calling methods from templates. I've personally been using this feature for months without any issues. However, recently I encountered a problem. I have a menu co ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

Supabase Authentication User Interface Error: Uncaught TypeError - Unable to access properties of null (specifically 'useState')

Concern Whenever I incorporate this Auth component into my login page, I encounter an issue. I am attempting to adhere to the guidelines provided in Supabase Auth with Next.js Pages Directory. If you suspect that this problem stems from a version discrepa ...

"Experience the power of angular-cesium by simultaneously opening four maps at once

Our current project is developed in Angular 7 with Angular Cesium serving as the map infrastructure. The application is currently operational on local PCs. A new requirement has come up which entails opening four different maps, each loaded with numerous ...

Leverage the state from a Context within a Class-based component

I have a Codepen showcasing my current issue. I want to utilize the class component so that I can invoke the forward function from parentComponents via ref. However, I am struggling with how to manipulate the context where the application's current st ...

Angular 2+ seems to be failing to detect and update changes in variables within the template

I have a component that includes rendering the user's name from the profile object. The corresponding part of the template looks like this: <button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()"> {{profile?.name} ...

Create a keyup function that triggers an alert message if the user's input does not meet the

Hello, I'm looking for some assistance with a coding problem. Basically, I have an array of numbers which includes 5, 8, and 10. I need to create a form where users can input numbers. If the user inputs a number that is not 5, 8, or 10, I want to disp ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

The upcoming development server will exclusively deliver HTML content without scripts or assets, mirroring the setup of the standard create-next-app template

In an attempt to recreate the problem I am facing, I decided to start by setting up a new Next.js app template folder using the command npx create-next-app (Version 13.1.6==latest, all default options, Node v18.14.0==LTS). However, when I try to run the pr ...

There seems to be a syntax error in the regular expression used in Angular TypeScript

I've encountered an error and I'm struggling to identify the syntax issue. core.mjs:6495 ERROR SyntaxError: Invalid regular expression: /https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2020-01-30,toDateTime ...

What is the reason this union-based type does not result in an error?

In my TypeScript project, I encountered a situation that could be simplified as follows: Let's take a look at the type Type: type Type = { a: number; } | { a: number; b: number; } | { a: number; b: number; c: number; }; I proceed to defi ...

Converting HTML to PDF with rtl support using the JavaScript library jsPDF

I'm attempting to convert HTML to PDF using jsPDF in an Angular 5 project. Below is the code I have so far: import * as jsPDF from "jspdf"; . . . htmlToPdf(){ var doc=new jsPDF(); var specialElementHandlers = { '#content' : function ...

Can a Bootstrap 5 modal popup be shown in Angular by utilizing an ngIf statement?

The issue we are facing here is related to the conditional display of a modal using ngIf. The problem arises because initially, when the page loads, the modal element is not present in the DOM as it is set to false by default. Therefore, on the first click ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...