Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django:

getConsumersMongodb(): Observable<any> {
    return this.httpClient.get(`${this.baseMongodbApiUrl}`);
}

The returned dictionary looks like this:

{
    "message": "Got all consumers' info successfully!",
    
    "consumers": {
        "id": 8, 
        "age": "51 - 60", 
        "gender": "Female"
        ...
    },
    
    "error": "Error!"
}

I only need the consumer data, so in my Angular component TypeScript code, I parse it out like this:

ngOnInit(): void {

    this.dbService.getConsumersMongodb()
      .subscribe(responseData => {
        this.loadedConsumersDict = responseData;
        this.consumersInfo = this.loadedConsumersDict["consumers"];
        console.log(this.consumersInfo);
      });
}

After retrieving the data, I want to convert the JSON object into an iterable array for display in my Angular HTML template. I updated my code to achieve this:

ngOnInit(): void {

    this.dbService.getConsumersMongodb()
      .subscribe(responseData => {
        this.loadedConsumersDict = responseData;
        this.consumersInfo = this.loadedConsumersDict["consumers"];
        let temp = this.loadedConsumersDict["consumers"];
        this.loadedConsumersArray = Object.keys(temp).map(function (key) {
          return { [key]: temp[key] };
        });
        console.log(this.loadedConsumersArray);
      });
}

However, the current output is not as expected. How do I properly format the data into an iterable array for easy display in my template?

<li class="list-group-item" *ngFor="let consumer of loadedConsumersArray">
    <p><i>Id:</i> {{ consumer.id }}</p>
    <p><i>Gender:</i> {{ consumer.gender }}</p>
    <p><i>Age Group:</i> {{ consumer.age }}</p>
    ...

I've made progress with displaying the data but now seeking assistance to properly structure it. Any guidance would be appreciated.

EDIT:

This is the relevant snippet from my Django's views.py script:

@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def handle_consumer(request):

    if request.method == 'GET':
        try:
            consumers = ConsumerModel.objects.all()
            consumers_serializer = ConsumerModelSerializer(consumers, many=True)
            # Fetch consumer data from MongoDB.
            print(consumers_serializer.data)
            # end fetch region
            response = {
                'message': "Got all consumers' info successfully!",
                'consumers': consumers_serializer.data[0],
                'error': "Error in GET try"
            }
            return JsonResponse(response, status=status.HTTP_200_OK)
        except:
            error = {
                'message': "Fail! Cannot get all consumers!",
                'consumers': "[]",
                'error': "Error in GET except"
            }
            return JsonResponse(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

And when printing the data, I ensure that it's structured correctly:

[OrderedDict([('id', 8), ('age', '51 - 60'), ('gender', 'Female'), ...])]

By accessing the first item in the list, I get the desired response:

{'id': 8, 'age': '51 - 60', 'gender': 'Female', ...}

Answer №1

users in the response is actually an object, not an array. This means there's no need to convert it into an array or use *ngFor.

Simply ensure that usersInfo is a public property, then in your template include the following:

<li class="list-group-item">
    <p><i>User ID:</i> {{ usersInfo.id }}</p>
    <p><i>Gender:</i> {{ usersInfo.gender }}</p>
    <p><i>Age Group:</i> {{ usersInfo.age }}</p>
    ...

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

Endless refreshing on ionic serve even when there are no file modifications

Issue Description While testing my ionic application build using the ionic serve command, I noticed that the app keeps recompiling as if triggered by a live reload, even when no files have been changed. This continuous recompilation process persists indef ...

List of images using React Native's FlatList

Seeking assistance with integrating images into a flatlist grid. I have successfully implemented text but struggling with images stored in the assets folder. The goal is to display separate images from the assets folder within the boxes of the flatlist gr ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

conceal the selected button upon moving to a different page

Whenever I click on the details button, it directs me to the details.html file. However, when navigating to another page, the details button still appears and I want to hide it in such cases. <button mat-button (click)="onSelectApp(app)"><mat-ic ...

Passing the value of the attribute from event.target as a parameter in a knockout click event

I have been exploring knockout events and am currently working on a functionality involving three buttons ("Packers", "Trail Blazers", and "Dodgers") within a div. Each button is associated with a data-league attribute of "NFL", "NBA", and "MLB," respectiv ...

Use Node-RED to fetch JSON or CSV data and store it in InfluxDB

Versions Node-RED v0.16.2 InfluxDB v1.2.2 Grafana v4.2.0 Ubuntu 16.04.2 I'm looking to access weather data from a local official weather station. The options available are in either csv or JSON format. I am attempting to retrieve the JSON feed us ...

Experiencing the issue with the $.getJSON function bug

Is there a way to ensure that my code processes the $.getJSON function fully? I am encountering an issue where only the first alert, 'inside1', is triggered when running the site. The second alert, 'inside x2', never gets processed. Any ...

Updating the DOM after every click event to keep content fresh

When the #undoAll button is clicked, it triggers individual click events using the following code: $('#undoAll').click(function(){ $('#prospectTable tbody tr td a:not(.invisible)').each(function(){ $(this).trigger('cli ...

"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four. Currently, the chart animates upon loading. How can I make it so that when #chartTrig ...

Next.js appending [object%20Object] to the URL's endpoint

I encountered an error when launching my next app using "npm run dev". The error occurred during the pre-render attempt: GET http://localhost:3000/aave/fundamentals/economics/[object Object] [HTTP/1.1 404 Not Found 434ms] The issue is not specific to thi ...

Unusual behavior observed in Angular 2 when handling button click events

In my .ts file, there are two straightforward methods: editLocation(index) {} deleteLocation(index) { this.locations.splice(index, 1); } The corresponding HTML triggers these methods when buttons are clicked: <button (click)="editLocation(i)" ...

Cannot find a compatible version for Angular2 Installation

Having trouble installing Angular 2. I followed the quickstart guide but still can't get it to install/start. npm ERR! Windows_NT 6.2.9200 npm ERR! argv C:....\\npm\\node_modules\\npm\\bin\\npm-cli.js ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...

Encountering a challenge when upgrading to eslint version 9.0.0

Encountering an issue while trying to upgrade eslint to version 9.0.0. ⋊> ~/A/fusion on turborepo ⨯ bun lint 22:21:58 $ eslint packages/*/src/**/* Oops! Something went wrong! :( ESLint: 9.0. ...

What is the method for changing the language of column names in a grid by simply clicking a button?

Greetings Everyone, I'm fairly new to angularjs and I'm seeking guidance on how to translate column names into another language on a grid by clicking a button. While I've managed to retrieve column names in English, I am unsure about how to ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

What are some ways to implement src imports in Vue3?

Can you guide me on using a component in VUE3 with composition API and script setup pattern? For example, let's say I have a component named Modal. Here is how I plan to structure the folder: Modal.vue - this file will contain the Vue template and ...