Exploring JSON object mapping and iteration in Angular2 using TypeScript

Within my application, I execute an http request that retrieves a JSON object.

To view the structure of the JSON, click here:

{
  "6288ba45-3b41-4862-9fed-7271245b9c29": {
    "id": "6288ba45-3b41-4862-9fed-7271245b9c29",
    "name": "name1",
    "possibilities": {
      "a48382bf-dde6-479d-8456-beee63f592be": {
      "id": "a48382bf-dde6-479d-8456-beee63f592be",
      "data": "anydata1",
      "style": null
      },
      "d62fb2d2-58a6-458c-9e7f-78774af4d9fe": {
      "id": "d62fb2d2-58a6-458c-9e7f-78774af4d9fe",
      "data": "anydata2",
      "style": null
      }
    }
  },
  "860aefe6-ff70-436b-8d2b-554251e8fb59": {
    "id": "860aefe6-ff70-436b-8d2b-554251e8fb59",
    "name": "name2",
    "possibilities": {
      "e30ef32b-20c2-4ddc-8d5f-e5f1fc35a6b7": {
      "id": "e30ef32b-20c2-4ddc-8d5f-e5f1fc35a6b7",
      "data": "anydata3",
      "style": null
      },
      "49e8b455-848c-4cb2-bb84-5b7b3bc5fc4a": {
      "id": "49e8b455-848c-4cb2-bb84-5b7b3bc5fc4a",
      "data": "anydata4", 
      "style": null
      }
    }
  }
}

My code snippet:

return this.http.get(`https://demo6902979.mockable.io/data`)
    .map((res: Response) => res.json())
    .filter((choices) => choices.id === "6288ba45-3b41-4862-9fed-7271245b9c29")
    .subscribe(
      data => {
        this.Data = data;
        console.log('Data:', data);
      },
      error => {
         console.log('Get data failed Error:', error);
      }
    );

https://i.sstatic.net/Kxn4W.png

Challenges with Filtering

I'm encountering difficulties while attempting to use the 'filter' method on this particular JSON structure in order to isolate the ID "6288ba45-3b41-4862-9fed-7271245b9c29". Unfortunately, it seems ineffective and doesn't return any results.

Trouble Iterating Through JSON Object

Due to the filtering issue, I temporarily remove the filter line and opt to iterate through the JSON object to extract data and style information. To access this data, for instance, using this.Data.possibilities.data (I am unsure how to retrieve possibilities ID to perform operations like

this.Data.possibilities.[UUID].data
or this.data.possibilities[0].data).

Navigating through the JSON within my code has proven challenging. The console outputs a JSON-formatted object, leaving me uncertain about the proper iteration method. I have attempted to utilize this.Data.forEach(), but encountered errors as forEach is not supported by the 'this.Data' element.

Most solutions available for Angular2 involve ngFor, yet I need to address this directly within the component class.

Your assistance is greatly appreciated. Thank you.

Answer №1

filter function is designed to work specifically on Arrays. However, in your case, the data you are working with is not an array.
One possible solution is to extract the keys of the object using Object.keys and then manipulate them accordingly.

var data = ...

Object.keys(a)
      .map(key => data[key]})
      .filter(choices => choices.id === "6288ba45-3b41-4862-9fed-7271245b9c29")
      .subscribe(data => {
          this.Data = data;
          console.log('Data:', data);
      },
      error => {
         console.log('Get data failed Error:', error);
      });

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

modify style when not valid and is touched

When I try to modify the style of an i tag based on the touched and invalid state of another field, only the input tag's style changes and not the i tag. Here's the CSS code I'm using: input.ng-touched.ng-invalid { border-color: red; } ...

What changes can be implemented to convert this function to an asynchronous one?

Is it possible to convert the following function into an asynchronous function? getHandledSheet(): void { this.timesheetService.getAllTimesheets().subscribe({next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => ...

Checking canActivate functionality in angular 2 using karma and jasmine: a guide

Looking to test the canActivate function in Angular 2 with TypeScript, Karma, and Jasmine. The code for the function is as follows: public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return t ...

What is the most effective approach for revealing AngularJS controller methods in TypeScript?

I have been exploring a way to attach the controller object to the scope in a different manner. Here is an example of how it can be achieved. interface IAppCtrlScope extends ng.IScope { info: any; } class InfoCtrl { header: string; name: strin ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

Having trouble with Angular 4 data display? See how to fix a simple example that's

I can't seem to display my data correctly in Angular. When I try, all I get are empty bullet points and an error message that says "Cannot read property of 0 undefined." Even though the code appears to be correct, it's not functioning as expected ...

"Encountering 'undefined' error in React JS console when accessing

I'm attempting to print the following: console.log(location_list.all_list[3]); console.log(location_list.all_list); However, I am getting "undefined" in one case. What could be causing this issue? https://i.sstatic.net/Xy0ge.png Additional code s ...

Troubleshooting: TypeScript not functioning properly with Create Next App dev server启动时有问题

When I attempted to set up a nextjs+typescript app using the command npx create-next-app@latest --ts, all the installations went smoothly. However, upon running the dev function, I encountered an error related to Global CSS. error - ../../../#Typescript/Ne ...

Angular 5 project encounters a 404 error while attempting to send a delete request to a .net web API

Whenever I try to send a delete request from my Angular 5 app to the .NET Web API, I receive a "DELETE http://localhost:51352/api/Account/undefined 404 (Not Found)" error. Below is the code snippet from my user.component.ts file in Angular: delete(id){ ...

Using Java to implement an embedded document structure in MongoDB through REST APIs

I am currently developing a REST service in Java that utilizes MongoDB (specifically the `mongodb-java-driver`), Jersey, and Jackson. One of the classes I am working with is the Employee class. public class Employee extends BasicDBObject { public Empl ...

Retrieving a distinct item from a JSON object using PostgreSQL

Within my PostgreSQL database, I have a JSONB field called "Data" storing the following JSON: { "CompetitionData" : { "StartDate" : "12.06.2018", "Name" : "TestCompetition", "Competitors" : [ { ...

Issue with Webpack Build Excluding JSON Resource Files

My Webpack build is not including the resources folder in the dist build, resulting in the translation files not being picked up and causing the translations to not take place... File structure: dist //The json files from src/resources need to be incl ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Issue with processing JSON data containing arrays and objects in Java Spring POST method

Using POST ajax from the frontend: Sending JSON array and object. Configured with : contentType: 'application/json' The JSON structure sent: { "alertKeeperDTOs": [ { "isSelected": true, & ...

AngularJS 2: Modifications to templates or components do not automatically reflect in the user interface

My background is in Angular 1, where everything worked seamlessly. However, I am encountering serious issues trying to create a basic application using Angular 2 in Visual Studio. After carefully following the "5 minute tutorial" and getting it to work, I ...

Accessing Angular2 form validation: receive a reference to ngForm

I'm trying to figure out how to have a reference to "myform" in the component. Is there a way to do this without using a formbuilder? I'd like to avoid that if possible. <form #myForm="ngForm"> <label class="col-sm-12" [class.ng-i ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Transforming a list into Json format within Robot Framework

Upon invoking a specific Get Regexp Matches function, I received the following list: ['{"result": 1, "error": { "namespace": "global", "reason": "unauthorized" } }'] While trying to verify values using the method below: Should Be Equal ${res ...

Creating a duplicate of a class and accessing its properties

Allow me to present what may seem like a Frankenstein's monster idea, but please hear me out. I have a specific type that I work with: export enum detailsDataTypes { MACHINE = 'MACHINE', USER = 'USER', ABSTRACT = 'ABSTRA ...