简体   繁体   中英

Spreading a json object into an iterable

In my Angular service script (following snippet) I receive a dictionary of customer data from my MongoDB database via Django:

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

The dictionary that comes back is like this:

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

I am only interested in consumers data, so I parse it out in my Angular component TypeScript code like this:

ngOnInit(): void {

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

Of course, in my dev console, I get this:

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

So far, so good...

Now, I need to convert this json object into an iterable, such as an array, so that I can go through its fields and display them in my Angular html template.

So, I modified my code to 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);
      });
}

But this gives me the following:

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

This is not what I want. How do I place the content into an iterable, so that I can simply use my following snippet in my html template code to display the fields?

<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 have come a long way to achieve this much, but now I am confused and need help. I would appreciate any help.

consumers in the response is an object and not an array. Therefore, you don't need to convert anything into an array, and surely no need to use *ngFor if you don't have to.

Just make sure that consumersInfo is a public property, and then in your template write the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM