Oliver Juhl
Oliver Juhl

Reputation: 115

How to transform multiple dates into a JSON object into custom formatted dates using moment.js?

I have a JSON object, that comes from an AJAX request, represented by an interface SuccesResponse

interface SuccessResponse {
    dates: Dates;
}

Where:

interface Dates {
    items: DatesItemResponse[];
}

interface DatesItemResponse {
    date: string;
}

A DatesItemResponse looks like this:

{
    "date": "2018-06-25T00:00:00"
}

I need to format all those dates using moment.js as MM-DD, so in the example above it should be 06-25, but I don't know how to make moment.js parse all the dates instead of a single one.

Upvotes: 1

Views: 715

Answers (1)

Danziger
Danziger

Reputation: 21161

According to the interfaces you mention, your response looks something like this:

const response = {
    dates: {
        items: [{
            date: '2018-06-25T00:00:00'
        }, {
            date: '2018-06-26T00:00:00'
        }, {
            date: '2018-06-27T00:00:00'
        }]
    }
};

Therefore, you need to iterate over items and parse all the date properties in there by creating a moment object with each date string and then calling format on those moment objects with the desired format, MM-DD in this case.

If you want to get all the dates in a single array, you could use Array.prototype.map() and do something like this:

const response = {
    dates: {
        items: [{
            date: '2018-06-25T00:00:00'
        }, {
            date: '2018-06-26T00:00:00'
        }, {
            date: '2018-06-27T00:00:00'
        }]
    }
};

console.log(response.dates.items.map(item => moment(item.date).format('MM-DD')));
<script src="http://momentjs.com/downloads/moment.min.js"></script>

However, if you want to get the exact same object you had initially, but with the original date strings replaced with the formatted ones, then Array.prototype.forEach() might be a better option (though technically, map would also work):

const response = {
    dates: {
        items: [{
            date: '2018-06-25T00:00:00'
        }, {
            date: '2018-06-26T00:00:00'
        }, {
            date: '2018-06-27T00:00:00'
        }]
    }
};

response.dates.items.forEach(item => {
  item.date = moment(item.date).format('MM-DD');
});

console.log(response);
<script src="http://momentjs.com/downloads/moment.min.js"></script>

Upvotes: 3

Related Questions