Arrange the date correctly based on the information retrieved from a JSON file

After retrieving a JSON file using an API, it looks something like this:

timeline: {
  cases: {
   '5/13/21': 5902343,
   '...' : ...
  },
}

This data is then used to create a chart using ChartJs.

The problem is that the dates in the JSON file are formatted as MM/DD/YY and I want to change them to DD/MM/YY.

Answer №1

Utilizing array destructuring is the key to solving this:

const labels = Object
  .keys(lineData.timeline.cases)
  .map((dateString) => {
    const [month, day, year] = dateString.split('/');
    return [day, month, year].join('/');
  });

const lineData = {
  timeline: {
    cases: {
      '01/06/2015': 12345,
      '05/11/2012': 12345,
    }
  }
}

const labels = Object
  .keys(lineData.timeline.cases)
  .map((dateString) => {
    const [month, day, year] = dateString.split('/');
    return [day, month, year].join('/');
  });
  
console.log("BEFORE", Object.keys(lineData.timeline.cases));
console.log("AFTER", labels);

Answer №2

If you want to transform items and create a new array, you can utilize the Array.map method in JavaScript. Here is an example:

labels: Object.keys(lineData.timeline.cases).map(day => {
    const dayArray = day.split('/');
    const month = dayArray.shift();
    return dayArray.splice(1, 0, month).join('/');
});

Alternatively,

You can also use the Array.map method to modify dates in an array like this:

const dates = ['5/13/21', '6/16/21'].map(date => {
  const [month, day, year] = date.split('/');
  return `${day}/${month}/${year}`;
  // return [day, month, year].join('/'); Or this
});

console.log(dates);

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 AngularJS to convert a JSON object into an array

Hey there, I've got a JSON return object that looks like this: color_selected = [ { id: 4}, { id: 3} ]; Any tips on how I can convert it to the following format? color_selected = [4,3] Appreciate any help or s ...

What is the benefit of using $q.all() with a single promise in AngularJS?

As I delve into this codebase, one snippet keeps popping up: $q.all([promise]).then(responseFunc); However, I find this confusing. After reading the documentation, I wonder why not simply use the following, as it's just a single promise... promise. ...

Getting Observable Centered Text in Angular with Chart.js

I have implemented ng2 charts and chart.js to create a doughnut chart. One of my requirements is to center text inside the doughnut chart, and I have tried the following approach: https://stackblitz.com/edit/ng2-charts-doughnut-centertext?file=src%2Fapp% ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Ionic timer binding issue: troubleshooting tips

Recently, I developed a stopwatch factory service that primarily focuses on running. Please disregard the reset and other functionalities as they are not yet implemented. Despite setting up $scope.time to capture timer changes, it doesn't seem to upd ...

An issue arises when attempting to initialize an AngularJS global variable using a REST service

I am looking to establish a global variable called httpTimeout that will be initialized at the beginning. This variable will contain a Long value retrieved from a synchronous Rest Service call and will be utilized in various services. ( function () { &apo ...

Implementing three identical dropdown menus using jQuery and HTML on a single webpage

It seems like I've tangled myself up in a web of confusion. I'm trying to have three identical dropdowns on a single page, each displaying clocks from different cities (so users can view multiple clocks simultaneously). However, whenever I update ...

The functionality of localStorage seems to be dysfunctional in Nuxt js when running in SSR mode

I am encountering an issue while trying to add items to a cart using vuex. The console is showing an error and the products on the page are not displaying correctly. Can someone please guide me on how to resolve this problem? The error in the console is: c ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

Guide on accessing the value within an array located inside an object

Hello everyone, I'm new to Angular and I need some help accessing the values inside objects. Specifically, I'm trying to access the SuccessCount in this Array. Here is my attempt: goodResponse=[ {compId: 1, companyName: "A", pendingCount: 0 ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

"Utilize an HTML input to query and retrieve data stored in a

Seeking to retrieve data from my MySQL database and display it on the website securely. List of existing files: /includes db_connect.php functions.php getdata.php logout.php process_login.php psl-config.php register.inc.php /j ...

Transform nested JSON objects into a JSON array using JavaScript

Hey there! I've got this JSON structure that I'm trying to convert into an array without having to iterate over each element. Is there a JavaScript function that can help me achieve this? { "ES": { "130": { "code": "A Coruсa", ...

What is the best way to update comments after submitting an AJAX request?

I stumbled upon a lightweight script that allows for submitting WordPress comments via AJAX. Although the comments are successfully submitted, the new comment does not appear immediately; only the comment count gets updated. Upon manually refreshing the pa ...

Is it possible for the children of a Three.js scene to have matrix positions that differ from the children of those children?

I am facing an issue with my ferris wheel. The baskets on the wheel are not aligning correctly when the scene is rotated: https://i.sstatic.net/Ek1mT.png Everything functions as intended until the scene is rotated, causing the baskets to misalign with th ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

Is there a way to merge two separate on click functions into one cohesive function?

I currently have two separate onclick functions as shown below. They are functioning properly but I am considering combining them for optimization purposes. Essentially, clicking on xx displays certain elements, hides others, and adds a class. Clicking o ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...