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.