Using the Javascript Foreach method to format dates results in displaying the identical date each time

Hello everyone,

I have been working on converting dates from my API using the moment.js library. The sample collection of dates retrieved from the API looks like this:

However, I am encountering an issue where all dates are returning as 2019-12-13, despite proper functionality in other parts of my codebase that implement moment.js.

const response = {
  data: [{
      'from': '2019-12-31T00:00:00',
      'to': '2020-12-31T00:00:00'
    },
    {
      'from': '2021-12-31T00:00:00',
      'to': '2022-12-31T00:00:00'
    },
    {
      'from': '2023-12-31T00:00:00',
      'to': '2024-12-31T00:00:00'
    }
  ]
}

response.data.forEach((d) => {
  d.from = moment(d.from).format("YYYY-MM-DD")
  d.to = moment(d.to).format("YYYY-MM-DD")
})

console.log(response.data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Answer №1

In your forEach loop, make sure to use d.to and d.from instead of response.data.to and response.data.from. Don't forget to include the variable d in your code:

response.data.forEach((d)=>{
   d.from = moment(d.from).format("YYYY-MM-DD")
   d.to= moment(d.to).format("YYYY-MM-DD")
});

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

Using JavaScript to change the date format of an RSS feed to Dutch format

I extracted this date from the RSS feed: "2014-02-28T20:00:00+0100" Is there a way to format it as: 28 February 2014 - 20:00? Looking for assistance on this formatting task! ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

Console is displaying an error message stating that the $http.post function is returning

Just diving into angular and I've set up a controller to fetch data from a factory that's loaded with an $http.get method connecting to a RESTful API: videoModule.factory('myFactory', function($http){ var factory = {}; facto ...

Express consistently receives an undefined JSON object as the request body

I've encountered an issue with my Ajax request and express setup. Here is the code snippet for my Ajax request: $.ajax({ url: '/gen', type: 'POST', data: JSON.stringify({'one': 1, 'two' ...

Why is the React Redux child component unable to access props?

Struggling with React and Redux? Here's the issue: A Component in my project is supposed to receive a value from Redux using mapStateToProps. The problem arises when trying to access this value within the child Component's renderFoo() function. ...

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

What strategies can I implement to combine postcss-bem with css-modules or postcss-js within a React component?

I am currently exploring the use of postcss-bem for generating CSS files in BEM style. I'm curious if there are other packages like CSS-Modules or Postcss-JS that could allow me to achieve something similar to the code snippet below: const ReactC ...

How to prevent AJAX form from reloading the page when using preventDefault()方法

I am currently working on a Node/Express/Mongo app and encountering an issue with an AJAX call. Despite using preventDefault(), the page continues to reload after data is saved successfully. Can someone help explain why this is happening? var categoryButt ...

Why does my camera suddenly switch to a rear-facing view when I begin my Zoom meeting?

I am facing an issue with my camera function where it initially starts off facing backwards, but as soon as I perform the first scroll, it flips around and works correctly. Please note that I am a beginner in coding. Kindly be aware that there is addition ...

Display AJAX content only after all images have finished loading

As I work on developing my own custom lightbox jQuery plugin, I have encountered a challenge. While everything seems to be functioning correctly, I am facing an issue where I want to hide the loaded content until all images have finished loading in the b ...

Error: The Mui Material Breakpoints Theme Cannot Be Located

Hello there! I'm having some trouble placing my code breakpoints, resulting in an error in the output. Can you help me? import { makeStyles } from "@material-ui/styles"; const useStyle = makeStyles((theme)=>({ LogoLg:{ display:&ap ...

Getting an integer array from a string array can be achieved by iterating through each

File myFile = new File( Environment.getExternalStorageDirectory().getAbsolutePath(), "Notes/test.txt" ); BufferedReader br = new BufferedReader(new FileReader(myFile)); String line = br.readLine(); while ((line = br.readLine()) != null) { b = l ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

Tips for making nested sliding divs within a parent sliding div

Is it possible to slide a float type div inside another div like this example, but with a white box containing "apple" text sliding inside the black div it's in? I have attempted to recreate the effect using this example. Here is my current JavaScript ...

Reorganizing a dask.array to follow Fortran-contiguous order

Is there a method available to reshape a dask array in Fortran-contiguous (column-major) order? I'm looking for an alternative since the parallelized version of the np.reshape function is currently not supported. Any suggestions or workarounds would b ...

How to ensure onmouseenter and onmouseleave work properly in Chrome using HTML, JavaScript, and jQuery

<div style="position: relative; left: 50px; top: 30px; width: 300px; height: 150px; background: #222222;" onmouseenter="this.style.background='#aaaaaa'" onmouseleave="this.style.background='#222222';"></div> http://jsfiddle ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

Modify the values within two arrays in JavaScript

As a novice, I am attempting to code a function that will change values within an array. Specifically, my goal is to convert ºC to ºK. However, the current code I have written is not functioning correctly and is throwing an error message stating "j is un ...

Is it possible to create a pause between fade-ins and fade-outs in a background slideshow

I am facing an issue with my background slideshow where the images start to fadeout immediately after the fadein effect is complete. I would like to create a pause between each picture before the next transition begins. Below is my code: HTML: <script ...

The location.reload function keeps reloading repeatedly. It should only reload once when clicked

Is there a way to reload a specific div container without using ajax when the client requests it? I attempted to refresh the page with the following code: $('li.status-item a').click(function() { window.location.href=window.location.href; ...