How to properly format a date object in Angular

After making a get request, I received JSON data in the following format:

{
"name" : "cow",
"date" : {
    "year" : 2012,
    "month" : "JANUARY",
    "dayOfMonth" : 1,
    "dayOfWeek" : "FRIDAY",
    "dayOfYear" : 1,
    "monthValue" : 1,
    "hour" : 2,
    "minute" : 2,
    "second" : 0,
    "nano" : 0,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
....
}

I want to convert the above JSON object into the following format using TypeScript/Angular:

{
"name" : "cow",
"date" : "2012-01-01"
}

Once converted, I need to store it in an array defined below.

//....correctFormat = [];
service.convertStore()
  .subscribe((data: any) => {
    // perform necessary manipulations here

    correctFormat = "holds the final result"
})

Answer №1

Extract the details for each member, create a new object for it, and add it to an array:

const obj = {
  "name": "dog",
  "date": {
    "year": 2015,
    "month": "APRIL",
    "dayOfMonth": 15,
    "dayOfWeek": "WEDNESDAY",
    "dayOfYear": 105,
    "monthValue": 4,
    "hour": 12,
    "minute": 45,
    "second": 30,
    "nano": 500,
    "chronology": {
      "id": "ISO",
      "calendarType": "iso8601"
    }
  }
}

const dateDetails = obj.date;
formattedData = [];
formattedData.push({
  name: obj.name,
  date: dateDetails.year + '-' + (0 + '' + dateDetails.monthValue).slice(-2) + '-' + (0 + '' + dateDetails.dayOfMonth).slice(-2)
});

console.log(formattedData)

Answer №2

If you want to define a custom class in Angular, you can follow these steps:

export class CustomClass {
   title: string;
   description: string;

   constructor(title: string, description: string) {
       this.title = title;
       this.description = description;
   }
}

Next, when invoking a service, use the following code snippet:

service.fetchData()
  .subscribe((response: any) => {
    // perform operations here
    const newData = new CustomClass(response['title'], `${response['date']['year']}-${response['date']['monthValue']}-${response['date']['dayOfMonth']}`);
    updatedData = "store the modified data"
})

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

Encountering a TypeError in Angular FormControl Jest test: Circular structure being converted to JSON issue

I encountered an error while running tests using Jest in my Angular project UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property &apos ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

Route.get() is expecting a callback function, however it received an object of undefined instead

In my nodejs application using typescript, I am working on separating the routing by introducing interfaces and controllers to handle the logic. app.ts const countryRoutes = require('./routes/countryroute') app.use('/countries', count ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

Utilize Angular Service Worker to prefetch API data efficiently (dataGroups)

I am working on an Angular website that needs to function offline. In order to achieve this, I need some data from the API, which can be considered Stale data. To handle this scenario, my approach is to first attempt to retrieve the data from the API, and ...

Discovering the ultimate guide to utilizing the ANT Design Menu.Item and Upload components side by side

I am currently using React, Typescript, and ANT Design for my project. One issue I encountered is with a menu item that is supposed to handle imports, but it's not displaying correctly: https://i.sstatic.net/hN1ch.png Below is the code snippet caus ...

I encountered numerous type errors while working on a React Native project that utilizes TypeScript

After following the instructions in the documentation to create a sample project, I used the command below: npx react-native init MyApp --template react-native-template-typescript Upon starting the project and running the command tsc I encountered 183 er ...

Issue with subscribing to nested observables, unable to successfully unsubscribe

My app is using Firebase auth with Firestore (https://github.com/angular/angularfire2). Despite my efforts to unsubscribe from all observables fetched from Firestore before signing out, I keep encountering a "FirebaseError: Missing or insufficient permissi ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Troubleshooting issue: Angular 7 form template not resetting with form.reset()

I'm having trouble resetting the input value and ngmodel control state in my form. Here's the code from TrackPage.html: <form #trackForm="ngForm"> <div class="form__field" style="padding-top: 10px; "> <search-in ...

Leveraging characteristics of combined types

Can anyone help me understand how to work with union and generic types by re-implementing something similar to Either or Option? Here is the code I have: type Error = { readonly _tag: 'error'; status: number; statusText: string; }; type Su ...

Having trouble determining whether a modal is currently open in an Angular application?

Greetings! I am currently working on a web application using Angular. Below is the code I have for opening a modal popup: this.formResetToggle = false; setTimeout(() => { this.formResetToggle = true; this.editorModal.s ...

Fetching Unicode block specials using axios in getStaticProps with Next.js

Click here to view the code and data results My attempt using the fetch method was successful, but I encountered issues when trying to use 'axios' ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Can more than one label be assigned to a single bar in a Google column chart?

Is it feasible to include an extra label on every column chart bar without affecting the appearance of the bar itself? This is how my current chart is arranged: this.populationChart.myChartObject.data = { 'cols': [ { id: 's&apo ...

Connecting JavaScript files in angular 4: A step-by-step guide

Currently, I am utilizing Angular 4 and looking to have my JavaScript file work globally. Here is how I have declared it in the index.html file: <script src="assets/js/jquery-1.11.1.min.js"></script> <script src="assets/js/bootstrap.min.js"& ...

How can the encapsulation parameter in Angular 2's component section be utilized effectively?

https://i.sstatic.net/CmVG2.pngI need some clarification on the encapsulation parameter in Angular 2. I encountered an error message when trying to utilize this parameter. How can I resolve this issue? @Component({ selector: 'app-add', ...

Surprising Logging Quirks in Angular

I've encountered a perplexing issue in my Angular app where an array is logged before adding an element to it, yet the log shows the updated array with the added element. This array is then utilized in an HTML file with ngFor. component.ts file inter ...

Hosting asynchronous bindings in Angular 2

I'm currently working on a component with the following code: @Component({ selector: 'my-selector', template: `<div>html code goes here</div> `, host: { '[style.background]': "'url(' ...

What is the best way to integrate JSON:API with Angular and RxJs?

Currently, I have a Laravel API that adheres to the json:api spec and functions smoothly with Postman for making requests on related resources. However, I am facing challenges in understanding how to utilize this API with my Angular front-end. To kickstar ...