I'm working with an array of objects that I've pulled from an API, but the content is currently in String format. How can I properly convert it into a date?

Utilizing the moment library, my array is structured as follows:

data:

[
            {
              "id": "610",
              "description": "New Test",
              "start": "2021-08-04T14:20:00.000Z",
              "end": "2021-08-04T15:30:00.000Z",
              "profile": {
                "firstName": "Steve",
                "lastName": "Tene"
              }
            },
            {
              "id": "610b",
              "description": "test",
              "start": "2021-08-03T13:30:00.000Z",
              "end": "2021-08-03T14:30:00.000Z",
              "profile": {
                "firstName": "Steve"
              }
            },
      ]

I attempted the following code snippet, but it seems that the map function only iterates through the array without making any changes.

data.content.map(x=>moment(x.start).toDate())

How can I create a loop to effectively convert the start and end strings into actual time values?

Edit: After trying out the solutions proposed by all of you, thanks for the prompt responses. Unfortunately, I encountered this error whenever I attempted anything, so I decided to provide more code snippets.

Error: Cannot assign to read only property 'start' of object '#'

  const [schedule, setSchedule] = useState([])
  useEffect(() => {
    const fetchData = async () => {
      const { searchavailable: data } = await searchAvailability()
      console.log(data.content)
      if (data) {
        data.content = data.content.forEach(x => {
          x.start = moment(x.start).toDate();
          x.end = moment(x.end).toDate();
      });
        setSchedule(data.content)
      }
    }
    fetchData()
  }, [schedule])

FIXED!!!!

Thanks to everyone for your valuable comments, with the use of deepClone from lodash, I was able to resolve the issue!

Answer №1

To update the beginning and ending times, you must assign values to those attributes. Utilize a forEach() function to loop through the array and set the correct values.

data.content.forEach(item => {
    item.startTime = moment(item.start).toDate();
    item.endTime = moment(item.end).toDate();
});

Answer №2

No libraries necessary. Simply input the string into the Date() function

data.content.forEach(item => {
   item.start = new Date(item.start);
   item.end = new Date(item.end);
});

Answer №3

It's best practice not to directly mutate data within React.

data.content = data.content.forEach...

Instead, consider making a copy of the data before making modifications.

data.content = [...data.content].forEach

Rather than replacing the original data.content value, you can save the modified data in a new variable.

You can try implementing the following code snippet:

const dataContent = [...data.content].map(x => {
  // Make necessary data changes here, like converting date formats
  x.start = new Date(x.start);
  return x;
});

setSchedule(dataContent);

Alternatively,

const dataContent = [...data.content];
dataContent.forEach(x => {
  // Make necessary data changes here, like converting date formats
  x.start = new Date(x.start);
});
setSchedule(dataContent);

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

How can I delete an item from an array when I click on a selected element using Material React Select Multiple?

I found this helpful CodeSandBox demonstration that walks through how to implement a multiple material select feature. Here is an array containing all the available options: const permissionsGroupList = [ { name: 'Sellers' }, { name: &a ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Dragging a stack of cards in a game of Solitaire using jQuery UI

I'm currently in the process of creating a Solitaire card game using Javascript. To enable dragging and dropping functionality for the cards, I am utilizing jQueryUI. In the example provided at http://jsfiddle.net/HY8g7/1/, you can see how the cards c ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

What is the best method for extracting string values from a JavaScript object?

I am working with JavaScript objects that look like this: {["186,2017"]} My goal is to extract and display only the values: 186, 2017 Initially, I attempted to use JSON.stringify thinking it was a JSON: console.log(JSON.stringify(data)); However, thi ...

A guide on transferring information to a database through a WYSIWYG HTML JavaScript editor in conjunction with Django

This morning, I dedicated my time to going through numerous tutorials on YouTube that explain how to build your own WYSIWYG editor. After testing the code in a controlled environment, it seems to function correctly and delivers the customization promised. ...

Ways to access the files attribute in an input tag in AngularJS without relying on getElementById

I am currently working on file uploads using AngularJS and I have a question regarding how to retrieve input files similar to regular JS. What I want to achieve: HTML: <input type="file" name="file" id="fileImg" accept="image/*"> JS: var file ...

Having trouble with yarn install? Keep receiving the error message "Other managers are not allowed"?

Recently, I began using the yarn package manager for one of my projects. To get started, I globally installed yarn using sudo npm install yarn -g. However, when attempting to install dependencies with yarn install, I encountered the following message on t ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

What is the best way to deactivate the second selection option?

<select id="title0"> <option value="0">--- disable</option> <option value="1"> books</option> </select> <button id="save" type="submit">Save</button> <select id="title1"> <option value="0"& ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

Code for remotely connecting to a server and starting a Node.js application called app.js via SSH

I am attempting to establish an SSH connection to two servers sequentially in order to execute the following command: sudo node app.js This is the code I am using: #!/bin/bash while read line; do ssh -i "sshtest.pem" ec2-user@$line "sudo node app. ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

The issue of memory leakage with ng-grid and real-time data

My intention is to utilize ng-grid for visualizing high-frequency real-time data, but I am encountering issues with a memory leak. Interestingly, the memory leak does not occur when I opt for a simple HTML table with ng-repeat. My tech stack includes node ...

Is there a way to calculate the product of two arrays of equal length and generate a new array containing these results?

public static double multiplyArrays(double u[][]) { double x[] = { 1, 2, 3 }; double y[] = { 4, 5, 6 }; for (int i = 0; i < x.length; i++) { for (double j = 0; i < y.length; j++) { double z = x[i] * y[i]; ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

What is the most effective approach to combining two arrays of objects in JavaScript by identifying commonalities?

Looking to merge two arrays of objects: var arr1 = [{id:1, name:John },{id:2, name:Adam }] var arr2 = [{id:1, address:NY, number: 200}, {id:2, address:LA, number: 300}] with the desired output being: var newArr = [{id:1, name:John, address:NY, number: 20 ...

Pressing the enter key in an AngularJS form does not trigger submission

Having trouble with a login form that won't submit when the user presses enter. While the form works fine when the "Login" button is clicked, hitting enter doesn't trigger submission and leads to some unexpected behavior: The ng-submit associat ...

Angular 4 is in need of CORS support

I have a server application with CORS enabled, which works well with my AngularJS client (1.x). However, I am now upgrading to Angular 4 and encountering the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the rem ...

Creating an array to store multiple ID values within a variable

const idArray = $scope.rep.Selected.id; I am working with this piece of code. I am wondering, if I have multiple ids in the $scope...Selected.id and then execute this (code), will all these ids be placed in separate arrays or combined into one array? ...