Converting JSON to Date in ES6/TS with Angular 2

Below is the JSON data:

let JSON_RESPONSE = `{"birthDates": ["2017-01-02","2016-07-15"]}`

There is a TypeScript object called Children with an array of Date objects and an ES6 constructor:

class Children {
  birthDates: Date[] = []

  constructor(values: Object = {}) {
    Object.assign(this, values)
  }
}

The goal is to initialize this object using the JSON data to convert the dates:

const children = new Children(JSON.parse(this.JSON_RESPONSE))
children.birthDates.forEach(it => {
  console.log(it.getDate())
})

However, since Children#birthDates are stored as Object types instead of Date, explicit new Date() initialization is needed:

children.birthDates.forEach(it => {
  console.log(new Date(it).getDate())
})

The question remains on how to convert JSON data to valid Date objects within the constructor without manual property mapping.

It seems that Object.assign is not suitable for deep type inheritance as it only performs a shallow copy.

Answer №1

To extract all values as dates, I would utilize the Array.prototype.map method in the constructor:

type Data = {
    birthDates: string[];
}

class Children {
    birthDates: Date[];

    constructor(values?: Data) {
        if (values) {
            this.birthDates = values.birthDates.map(value => new Date(value));
        } else {
            this.birthDates = [];
        }
    }
}

(code in playground)


Edit

If additional fields are present in the data, you can utilize Object.assign to merge them and then update the birthDates property with the mapped values:

interface IChildren {
    size: number;
    groupId: string;
    birthDates: string[];
}

class Children {
    size: number = 0;
    groupId: string = null;
    birthDates: Date[] = [];

    constructor(values?: IChildren) {
        if (values) {
            Object.assign(this, values);
        }

        this.birthDates = this.birthDates.map(value => new Date(value));
    }
}

(code in playground)

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

Utilizing ionic-scroll for seamless movement and scrolling of a canvas element

I have set up a canvas element with a large image and I want to enable dragging using ionic-scroll. Following the provided example: <ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px"> <div style="width: 5000px; h ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

Having trouble interpreting the Json response from a jQuery Ajax POST request

When I receive a JSON from a REST API via Ajax, if I print the result to the console and then save it into a string variable (jsonInput) `JSON.parse` works without any issues. However, when I directly use the data from the Ajax call, it returns as undefi ...

Retrieve an image located outside of a container

I have multiple SVGs inside separate div elements. <div id="divA"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

My Python program is receiving a "400 Bad Request" error from the Strawpoll.me API, yet the API functions properly when accessed through the terminal

I recently wrote a Python program to generate strawpolls using the API provided by strawpoll.me. You can find more information about the API here. import aiohttp import asyncio async def createPoll(): question = "Is this thing on?" options = ["Ye ...

Begin by opening a single div for each instance

I want a functionality where opening one div closes all the others. I've searched around for solutions and only found jQuery options, not pure JavaScript ones. Here is my code: function openDescription(description_id) { var x = document.getEle ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...

My Angular-based todo application has encountered an error notification from the system

Every time I try to post something, the system responds with a 405 error message in the console. I'm not sure what caused this issue or how to resolve it. Alternatively, if I click the done button, the console displays a 500 error message. Here is t ...

The function createReadStream completes execution without resolving

Currently, I am in the process of developing a program that is aimed at iterating through files within a specified directory in a Linux environment. I have implemented a custom function called "myReadFile" which returns a new promise, and it is expected ...

The function that iterates through the 'categoria' state and returns a new array is not functioning properly

Having difficulty with the object of a function using .map(). It works when the code is used directly, but not when put inside a function. For example: if(this.state.cat){ return _.map(this.state.cat, categoria => { if(this.state.search_ ...

Encountering an error when attempting to retrieve the value of a JToken - Unable to retrieve child value from Newtonsoft.Json.Linq.J

Currently I am in the process of developing a test case to simulate my C# method. Unfortunately, when trying to retrieve the DocumentID property of the JToken using token["DocumentID"], I am facing issues. Specifically, I am receiving a System.InvalidOpe ...

Utilize the data-toggle attribute to retrieve a unique variable name, which can then be integrated into a function for added

I'm in the process of replacing an iframe with an image, and I want to accomplish this with minimal code. The container div I'm working with has a data-toggle attribute: <div id="my-div" data-toggle="video2"> <div id="videocontaine ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Step-by-step guide to creating a flip effect with Angular 2 animations

I've been utilizing pure css flip of cards in my project, but I feel like it's not the best solution. Does anyone know how to create a card flip in angular 2 upon clicking a button? I came across one in angularjs here <div ng-app="cardFli ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Retrieve the content of a specific HTML tag using JavaScript

Is it possible to extract the content of a specific HTML tag as a string or XML format? <body> <script src="jquery.min.js"> //var test = document.getElementsByTagName("input"); //alert(test[0]); $(document).ready(function ( ...