What is the process of transforming an array of date strings into actual dates?

Looking for assistance in converting an array of date strings to actual Date objects.

Here is the input data:

medicalData = [
  {
    name: 'Allergy',
    status: 'Normal',
    testDates: ['2023-07-02T13:21:29.643Z', '2023-07-03T13:21:29.644Z']
  },
  {
    name: 'Asthma',
    status: 'Deficient',
    testDates: ['2023-08-02T13:21:29.643Z', '2023-08-03T13:21:29.644Z']
  }
];

In my medical.service.ts file:

const result = await this.medicalRecordRepository.create({
    medicalData: medicalData // need guidance on using new Date() here
});

Within medical.schema.ts:

class MedicalData {
  @Prop()
  name: string;

  @Prop()
  status: string;

  @Prop()
  testDates: [Date];
}

export class MedicalRecord extends Document {
  @Prop()
  medicalData: MedicalData[];
}

I want the testDates to be stored in the database as an array of dates, not strings.

Any valuable assistance would be greatly appreciated.

Answer №1

An effective method involved double mapping the medical data:

  • The outer map function is used for each entry in the medical data, utilizing destructuring, rest property for arguments, and spread syntax to create a copy of the data entry.
  • Within this, there is a nested map that creates another version of the testDates array for each entry, with its items being instances of the Date object.

const medicalData = [{
  name: 'Allergy',
  status: 'Normal', 
  testDates: ['2023-07-02T13:21:29.643Z', '2023-07-03T13:21:29.644Z'],
}, {
  name: 'Asthma',
  status: 'Deficient',
  testDates: ['2023-08-02T13:21:29.643Z', '2023-08-03T13:21:29.644Z'],
}];

/* 
const result = await this.medicalRecordRepository.create({
  medicalData: medicalData.map(({ testDates, ...rest }) => ({
    ...rest,
    testDates: testDates.map(dateStr => new Date(dateStr))
  }))
});*/

console.log({
  medicalData: medicalData.map(({ testDates, ...rest }) => ({
    ...rest,
    testDates: testDates.map(dateStr => new Date(dateStr))
  }))
});

Note:

The specific logging in this example may display Date instances as stringified versions, but a browser's console would show them as actual date objects.

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

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Using Angular NgRx - triggering an action from an effect once certain actions yield a result

I'm encountering difficulties in dispatching actions that require results from five other actions (all listed in my effect). Could someone lend a hand? Essentially, I need to trigger an action within the effect only after these five actions have retu ...

Timeout of 30 seconds added to Axios network requests in Javascript

self.$axios .$get( `https://verifiedpro.herokuapp.com/getvmsstate?kiosk=${self.kiosk}` ) .catch(error => { console.log(error); location.reload(); }) .then(response => { console.log(respons ...

A guide to fetching JSON data with Mongoid

Below is the model I am working with: class Client include Mongoid::Document field :name, type: String field :age, type: Integer index({ name: 1 }, { unique: true }) def self.list self.all.as_json end end After calling Client.list, I rec ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Tips for refreshing an Angular app on all pages periodically:

Currently I am working on developing an application using Angular, MongoDB, and Nodejs as the backend. However, I am facing an issue where I have to manually refresh the Angular page every time I add an image or make any changes in order for them to appear ...

What is the best way to transfer an array between different pages?

I'm attempting to transfer an array between pages. page1: session_start(); $input01 = array("img01.png", "img02.png", "img03.png); $_SESSION['input01']=$input01; page2: session_start(); shuffle($input01); Outcome: Warning: shuffle( ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

What is the best way to observe objects in Vue.js?

I have an object containing longitude and latitude coordinates? data(){ return{ center2:{lat:0,lng:0} } } I am attempting to watch these values but it's not working as expected watch:{ "center2.lat":function (newValue, oldValue) { ...

Scraping the web with cheerio: Should we delete or disregard a child element?

There's a specific website I'm looking to scrape, and its structure is as follows: <p><strong>a certain heading:</strong> some information etc. blabla </p> <p><strong>another heading:</strong> more deta ...

Exploring the nuances of MYSQL date calculation methods: Unpacking the variance between DATE_ADD and using a simple + INTERVAL

Apologies if this question has been asked before, but I haven't been able to find an answer here or anywhere else. I've gotten accustomed to calculating dates in MYSQL using functions like DATE_ADD and DATE_SUB as outlined in this documentation: ...

Positioning a div on the right side of its parent div

Hi there! I'm currently working on a small navbar that has two sections: the left section with an arrow icon and the right section with two icons - an envelope and an exclamation triangle. I've been trying to position the right section in the top ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Testing an ajax-driven website: what's the best approach?

Seeking to develop automated tests for my completely ajax-based website developed using Spring MVC/Java. I possess a basic understanding of Selenium and have managed to create some tests using this tool. The main issue lies in the fact that testing an aja ...

Is there a way to delay loading 'div' until a few seconds after the 'body' has been fully loaded?

Is there a way to delay the appearance of the "text-container" div after the image is displayed? I have attempted to achieve this using JavaScript with the following code: <script> window.onload = function(){ var timer = setTimeout("showText()",700 ...

The hamburger menu is only functional for a single link

I've been developing a hamburger menu for my website, and it seems to be working fine until I click on a link. Once I navigate to a new page, the menu stops responding. To fix this issue, I attempted to use window.location.reload, which worked in Chro ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Is there an issue with the real-time update of graphics pixels in Java?

At this moment, my main goal was to display my game window on the screen. However, I encountered an issue where the color red is not displayed across the entire window. I have reviewed my code multiple times but can't seem to identify the problem. Her ...

The dynamic array is limited to allocating just a single element

After extensive searching, I have come up empty-handed on this issue. The code snippet in question is as follows: #include<iostream> using namespace std; int main() { int *newArray; int size; cout << "enter size: "; cin >> size; new ...