1

I am having some trouble figuring this out. I have a Json response:

[
  {
    "id": 82797,
    "name": "pom-ta-all",
    "date": "2016-06-26T11:57:53+0000",
    "creationDate": "2016-06-10T14:15:00+0000",
    "version": "1.0.0",
  },
  {
    "id": 80926,
    "name": "pom-evnthdl-wln-all",
    "creationDate": "2016-06-03T17:44:20+0000",
    "version": "1.1.0",
  }...

that I get from rest api using Jquery Ajax. How do I, in the Ajax call, add the current date to each element so that it looks like so:

[
      {
        "id": 82797,
        "name": "pom-ta-all",
        "date": "2016-06-26T11:57:53+0000",
        "creationDate": "2016-06-10T14:15:00+0000",
        "version": "1.0.0",
        "currentDate": "2016-06-28"
      },...

Can I use .append()? if so, how? I am not very familiar with Ajax and JavaScript in general. It would be best if the format was like so:

var job = $.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: #insert magic here, <---
    error: function()
  });

Thanks for your thoughts

Jim Wu
  • 149
  • 1
  • 8
  • 3
    This has nothing to do with Ajax. You need to learn the basics about objects. Maybe these help: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196), [How can I add a key/value pair to a JavaScript object?](http://stackoverflow.com/q/1168807/218196). – Felix Kling Jun 28 '16 at 14:51
  • You can use map to iterate over the array and get the new desired array: jsonResponse.map(i=>i.currentDate = new Date() && i) – Jose Hermosilla Rodrigo Jun 28 '16 at 14:57
  • You're right, Sorry about that, removed the tag – Jim Wu Jun 28 '16 at 14:59

1 Answers1

2

Your success function

...
success: function(json) {
    $.each(json, function(idx) {
       json[idx].currentDate = new Date();
    });
}
...

Working Example, based on your inputData

var json = [
  {
    "id": 82797,
    "name": "pom-ta-all",
    "date": "2016-06-26T11:57:53+0000",
    "creationDate": "2016-06-10T14:15:00+0000",
    "version": "1.0.0",
  },
  {
    "id": 80926,
    "name": "pom-evnthdl-wln-all",
    "creationDate": "2016-06-03T17:44:20+0000",
    "version": "1.1.0",
  }];
  
  
  
  $.each(json, function(idx) {
     json[idx].currentDate = new Date();
  });
  
  console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How you get current date formatted with JS see suggestion from other guy:

How do I get the current date in JavaScript?

Community
  • 1
  • 1
pleinx
  • 616
  • 3
  • 8
  • Hi, that code works for the most part, but I the `new Date()` was wonkey so I followed your link to the other way of getting the date. Thanks! – Jim Wu Jun 28 '16 at 15:35