Convert an object to nested JSON in Angular 5

I am struggling with using Angular 5 HttpClient to send a post request because I am having trouble casting an object to nested JSON. For instance, I have the following class:

export class Team {

    members: Person[];

    constructor(members: Person[]) {
            this.members = members;
    }
}

export class Person {

    name: string;
    gender: string;
    ...

    constructor(...) { ... }
}

The desired JSON body structure should look like this:

{

    "members" : [
            {
                    "name" : someone01,
                    "gender" : ...,
                    ...
            },
            {
                    "name" : someone02,
                    "gender" : ...,
                    ...
            },
            ...
    ]
}

Can someone please advise me on how to achieve this? Thank you in advance.

Answer №1

If your data structure matches the JSON output, consider using json.stringify

const jsonstring = JSON.stringify(yourModel);

To create a nested JSON structure, you can follow this format

'members': membersCollection.map(element => ({
            'name': element.name,
            'gender': element.gender,
            'addresses: [element.Addresses.map(address=> ({
                        'city': address.cityName,
                        'country': address.country,
                        })]
        })),

It is recommended to break down nested classes into smaller methods for improved readability.

const body ={

'members' : [getMemebers(someClass)],
'addresses' : [getAddresses(someClass)],
};

Ensure the validity of the JSON using a tool like jsonlint before implementation.

Answer №2

Implement this code snippet for a practical demonstration:

import { Component } from '@angular/core';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
})
export class SampleComponent {
  title = 'sample';
   values = data.members;
}

export class Squad {
  members: Individual[]
}

interface Individual {
  name: string;
  gender: string;
}

const data: Squad = {
  "members" : [
          { 
                  "name" : 'person01',
                  "gender" : 'm',

          },
          {
                  "name" : 'person02',
                  "gender" : 'f',

          },
  ]
}

To showcase the data, you can incorporate the following code in your 'sample.component.html':

<table>
      <tr *ngFor="let person of values">
        <td>{{person.name}}</td>
        <td>{{person.gender}}</td>
      </tr>

</table>

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

What is the best method for generating an inline keyboard using JSON with several InlineKeyboardButton elements on a single row?

Seeking a JSON payload to generate an inline_keyboard with multiple InlineKeyboardButton on the same row. The current code provided is functional but produces one button per row. { "telegram": { "text": "Choose a color", "reply_markup": { ...

Deserializing Jackson JSON-RPC to a universal Object

Deserializing a JSON-RPC object with Jackson has been a challenge for me. The structure of the JSON-RPC is as follows: { "result": "something", "error": null, "id": 1} Specifically, my issue lies in the result property being a generic Object. To tackle ...

Send a PHP object to JavaScript using AJAX

I have a PHP script that successfully uploads a video to the Microsoft Azure service using an API. The API returns a StdObject file, which I then want to send back to JavaScript via AJAX. However, when I try to access the "asset" object in JavaScript, it a ...

Angular's NgShoppingCart is designed in such a way that items stored in the localStorage are automatically cleared out

I am currently working on an Angular project using version 8.0.0. To integrate a shopping cart feature into my Angular project, I decided to incorporate the NgShoppingCart library by following the instructions provided here. After adding the library in m ...

Encountering a 500 Internal Server Error while using passport-jwt in a MEAN-Stack application

Using the passport.js JWT strategy to authenticate my MEAN-Stack app has been successful for unsecured routes, but I'm encountering issues with secured routes. Despite following the documentation, all secured routes consistently return an Internal Ser ...

Is there a way to merge all this data into a single Object?

This particular situation is quite complex. Let's consider the following scenario: I have two JavaScript objects that are fetched via REST calls, using two different callbacks. So, we have: call1() - POST method - parsed JSON to JavaScript object, ...

Is it possible for dynamically created components to trigger output events?

My objective: Dynamically create components (completed) Enable dynamically created components to utilize "outputs" so that parent Components can listen for changes from the children. Here is a Plnkr showcasing what I am trying to achieve: Plnker -> ...

Next.js allows for the wrapping of a server component within a client component, seamlessly

I am currently working on a project where I have implemented a form to add data to a JSON using GraphQL and Apollo Client. The project is built with TypeScript and Next.js/React. However, I am facing a conflicting error regarding server client components ...

TS interfaces: Understanding the distinction between optional and mandatory properties

In this example, I am demonstrating TypeScript interfaces in a simple way: interface A: { id: number; email: string; } interface B extends A { login: string; password: string; } My goal is to have certain requirements when creating objects fr ...

Visualize complex JSON data within an Angular Material Table

The JSON file is structured as follows: { "products": { "items":[ { "productId": "1", "dept": "home", "itemtype": "small" }, { "productId": "2", "dept": "kitchen", "itemtype": "medium" ...

The process of showcasing an enum value in RestAPIs

There is a defined enum class called Size: enum class Size { SMALL("1-50"), MEDIUM("51-1000"), LARGE("1001-5000"), EXTRA_LARGE("5000+"); } How should this be presented to users of the API? If we were ...

Testing an action within an interval in Angular using Jasmine

Looking to run a jasmine test on this method: public init(): Subscription { return interval(100).subscribe(() => this.doSomething()) } The goal is to verify that the doSomething method gets executed when the init function is called. We are usi ...

Set an interface to null within Angular 4

I've created an interface in Angular 4 called StatusDetail: interface StatusDetail { statusName: string, name: string } Next, I assigned some values to it within an Angular component: //Angular Component export class EditComponent implemen ...

In what ways can I enhance and visually improve JSON data using a jquery/javascript plugin?

My current project requires me to display JSON data received from the backend in a textarea. However, the data comes unformatted and not validated. Now I'm facing two main challenges: 1) How can I beautify the JSON content in the textarea? 2) How can ...

Persistent Storage on Android Devices

After exploring the Android Storage Options, I have a question that remains unanswered: When it comes to storing my data, should I opt for SQLite or utilize a JSON object written to a file? My Requirements: I need to store several hundred instances of th ...

I encountered an issue when attempting to display a validation message on an Angular form

As I work on creating an Angular form and implementing validation, I encountered an issue when attempting to display a message when a field is left empty. My approach involved using ng-for in a span tag, but unfortunately, an error occurred. Here is the H ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

What is the best method for setting a dash as the default value in a template?

My HTML code in Angular 8 includes the following: <span>{{post.category || '-'}}</span> If post.category is empty, a dash is shown as expected. However, I am facing two other situations: <span>{{post.createdAt || '-&apo ...

Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console? I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation? data:[object Object] text:Data is supplied by Government ...

When using npm to install Angular Bootstrap, the versions that are installed do not always match the specific versions

Displayed below is the content of my package.json file. { "name": "MyProject", "private": true, "version": "0.0.0", "scripts": { "test": "karma start ClientApp/test/karma.conf.js" }, "devDependencies": { "@angular/animations": "5.0.2", "@angular/common": ...