Skip to content Skip to sidebar Skip to footer

Put A Date In The Correct Order From A Json File

I recover thanks to an API a json file made up like this : timeline: { cases: { '5/13/21': 5902343, '...' : ... }, } which then aims to constitute a chart with ChartJs E

Solution 1:

You can leverage array destructuring to achieve 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);

Solution 2:

You can use the Array.map method to create a new array with transformed items like:

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

Or

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);

Post a Comment for "Put A Date In The Correct Order From A Json File"