Search code examples
arraysangularjslodashangular-moment

Changing time format in an array using moment and angularjs and lodash


I have Json data which has timings based on dates.

obj = {
"2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
],
"2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
],
"2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
]
}

I want to convert this json object into the format below:

obj = {
"2017-12-08": ["13:00","15:00","15:30","16:00"],
"2017-12-09": ["09:00","09:30","10:00"],
"2017-12-10": ["09:00","09:30","10:00","10:30"]
}

Currently I'm using a for loop to traverse through each element in the array and then replace each element using

obj[Object.keys(obj)[date]][time]=moment(obj[Object.keys(obj)[date]][time]).format(HH:mm);

how do i accomplish this using lodash , moment and angularjs?


Solution

  • You can use _.forOwn() to loop over your object properties, _.map() to loop over each array items and use momentjs to change the item format.

    This is how should be your code:

    _.forOwn(obj, function(value, key) {
       obj[key] = _.map(value, function(item) {
          return moment(item).format("HH:mm");
       });
    });
    

    Demo:

    var obj = {
      "2017-12-08": [
        "2017-12-08T13:00:00+0530",
        "2017-12-08T15:00:00+0530",
        "2017-12-08T15:30:00+0530",
        "2017-12-08T16:00:00+0530"
      ],
      "2017-12-09": [
        "2017-12-09T09:00:00+0530",
        "2017-12-09T09:30:00+0530",
        "2017-12-09T10:00:00+0530"
      ],
      "2017-12-10": [
        "2017-12-10T09:00:00+0530",
        "2017-12-10T09:30:00+0530",
        "2017-12-10T10:00:00+0530",
        "2017-12-10T10:30:00+0530"
      ]
    };
    
    _.forOwn(obj, function(value, key) {
      obj[key] = _.map(value, function(item) {
        return moment(item).format("HH:mm");
      });
    });
    
    console.log(obj);
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>