Skip to main content
Bumped by Community user
Bumped by Community user
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Source Link
Geraint
  • 273
  • 2
  • 4
  • 10

Convert all dates in an array to date format

I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates

The backend uses Node.Js and queries a mySql database with the mySql module:

pool.getConnection(function(err, conn) {
  conn.query('SELECT * FROM myData’, function(err, result) {
    if (result) {
      res.json(result);
    }
    conn.release();
  });
});

An Angular.js front end accesses the Express API.

var _getCases = function() {
  return $http.get('/api/case');
};

But the dates are all strings. Here’s an example of what's received in Angular:

[
  {
    id: 1,
    fruit: “apple”,
    createdOn: "2016-09-02T23:00:00.000Z"
  },
  {
    id: 2,
    fruit: “banana”,
    createdOn: "2016-09-11T23:00:00.000Z”
  },
  {
    id: 3,
    fruit: “cherry”,
    createdOn: "2016-09-13T23:00:00.000Z"
  },
]

I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?

var a = $http.get('/api/case');

for(var i in a){
  a[i].createdOn = new Date(a[i].createdOn);
};

return a;