Separating JSON events into monthly categories using JavaScript

I need to organize a list of events by the month they are scheduled to take place. Currently, I have an array with JSON objects for each event, but I want to display them in a specific format:

January
- event blabla 10/01/17
- event thisandthat 17/01/17

February
- event something 05/02/17
- event another something 13/02/17

...and so on

The way the JSON data is structured currently doesn't allow me to achieve this desired output. Is there a method to manipulate the JSON data to suit my needs?

This is how I am currently receiving my JSON data:

[{
    "event_name": "blabla",
    "event_location": "somewhere",
    "event_date": "2017-01-10" 
},
{
    "event_name": "blabla",
    "event_location": "somewhere",
    "event_date": "2017-01-10" 
},
{
    "event_name": "blabla",
    "event_location": "somewhere",
    "event_date": "2017-02-10" 
},
{
    "event_name": "blabla",
    "event_location": "somewhere",
    "event_date": "2017-03-20" 
},
{
    "event_name":"blabla",
    "event_location":"somewhere",
    "event_date":"2017-05-05" 
}]

The expected result should resemble this structure:

[{
    "January": [{
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-01-10" 
        },
        {
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-01-17"
        }
    ]
},
{
    "February": [{
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-02-10"
        },
        {
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-02-17"
        }
    ]
},
{
    "March": [{
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-03-10"
        },
        {
            "event_name": "blabla",
            "event_location": "somewhere",
            "event_date": "2017-03-17"
        }
    ]
}
]

Is it possible to transform the existing JSON data into this new format?

Answer №1

One way to accomplish this task is by utilizing Array#reduce:

var information = [{
    "example_name": "ex1",
    "example_location" : "there",
    "example_date": "2017-01-10" 
},
{
    "example_name": "ex2",
    "example_location" : "here",
    "example_date": "2017-10-17" 
},
{
    "example_name": "ex3",
    "example_location" : "everywhere",
    "example_date": "2017-02-10" 
},
{
    "example_name": "ex4",
    "example_location" : "nowhere",
    "example_date": "2017-03-20" 
},
{
    "example_name": "ex5",
    "example_location" : "somewhere",
    "example_date": "2017-05-05" 
}];

var monthList = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var groupsInfo = information.reduce(function(acc, obj) {
  var month_data = monthList[new Date(obj.example_date).getMonth()];
  acc[month_data] = acc[month_data] || [];
  acc[month_data].push(obj);
  return acc;
}, {});

var final_result = Object.keys(groupsInfo).sort(function(x, y) {
  return monthList.indexOf(x) - monthList.indexOf(y);
}).map(function(key) {
  var object = {};
  object[key] = groupsInfo[key];
  return object;
});

console.log(final_result);

Answer №2

If you want to organize them by months, one way is to loop through the events and create a new object with each event categorized by its respective month:

let unorganized = [{
    "event_name": "blabla",
    "event_location" : "somewhere",
    "event_date": "2017-01-10" 
},
{
    "event_name": "blabla",
    "event_location" : "somewhere",
    "event_date": "2017-01-10" 
},
{
    "event_name": "blabla",
    "event_location" : "somewhere",
    "event_date": "2017-02-10" 
},
{
    "event_name": "blabla",
    "event_location" : "somewhere",
    "event_date": "2017-03-20" 
},
{
    "event_name": "blabla",
    "event_location" : "somewhere",
    "event_date": "2017-05-05" 
}];

let organized = {};
let months = 'January February March April May June July August September October November December'.split(' ');

unorganized.forEach(event => {
  let date = new Date(event.event_date);
  let month = date.getMonth();
  let monthName = months[month]
  if (!(monthName in organized)) {
    organized[monthName] = [];
  }
  
  organized[monthName].push(event);
});

console.log(organized);

Alternatively, you can utilize lodash library to achieve the same result more concisely:

organized = _.groupBy(unorganized, e => months[new Date(e.event_date).getMonth()])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for dealing with Uncaught Error: [nuxt] store/index.js must have a function that returns a Vuex instance

In my Nuxt project, I have set up a default store in Nuxt within the store/index.js file as per the guidelines provided in the documentation. However, upon trying to render my app, I encounter the following error: Uncaught Error: [nuxt] store/index.js sh ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Managing multiple ajax requests only functions properly when notifications are raised

I'm looking to efficiently transfer data to the server from multiple lists on a page by using ajax calls to process the information in PHP. My code iterates through each list with the class "dd" and sends the ajax data one by one. Everything works smo ...

Invoke the jQuery document.ready function within a separate jQuery or JavaScript function

Encountering a difficult issue: Attempting to invoke the document.ready() function inside another JavaScript function, but upon doing so, an error message stating "function is not defined" appears. Below is the provided code: This first function serves as ...

Issue with zeroLineColor and zeroLineWidth not functioning properly for the x-axis within Chartjs

Looking to customize the width and color of the x-axis in Chartjs? While it's straightforward for the y-axis using zeroLineColor and zeroLineWidth, achieving the same effect for the x-axis seems trickier. If you try adding: ticks: { beginAtZero: tr ...

Troubleshooting a Dysfunctioning Character Counter Feature in a JavaScript Input Field

I've been working on a fun little project to practice my JavaScript skills - a plate calculator. Here's the gist: you enter your name, and each letter costs $5, so the total cost of the plate is the length of your name multiplied by $5 (this pro ...

Is there a way to easily deserialize a JSON object that doesn't have a specified name and is constantly

In the JSON provided below, you will find error messages for various properties: { "username": [ "A user with that username already exists." ], "ruc": [ "user with this RUC already exists." ], "code": [ "user wi ...

JavaScript - splitting numbers into multiple parts

Need help with a JavaScript question regarding numbers like 2,5 or 2.5 I attempted to perform a multi-split operation using the following code: '2.5'.split(/,|./) However, it resulted in an incorrect output: ["", "", "", ""] ...

Troubleshooting the Issue with Counting JSON Nodes in AJAXейства

So, I have this JSON snippet: { "productDetails": { "productThumb": "/uploads/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="215544525560454c484f614548594e4f424e4c0f424e4c">[email protected]</a>/showup-bg4.jp ...

Creating a universally accessible handlebars helper in ExpressJS

I have a basic handlebars helper file located in helpers/handlebars.js: var hbs = require('express-handlebars'); hbs.registerHelper("inc", function(value, options) { return parseInt(value) + 1; }); Unfortunately, I am unable to utilize the ...

Challenges encountered when converting Javascript into a Django template

I am facing a challenge with converting an HTML file into a Django template. It appears that the main.js file is not functioning properly, yet there are no errors being displayed in the debug console. I recently transferred the files from my local filesys ...

Error Found: The function .setFromEuler() in THREE.Quaternion now requires an Euler rotation as input instead of a Vector3, along with its corresponding order

In my ThreeJS/WebGL project, I have created a rotating planet displayed inside an iframe. While the functionality is working as intended, I am encountering a warning and an error: Warning: THREE.WebGLRenderer: Texture is not power of two. Texture.minFilte ...

Is there a way to access the Google Maps instance without the need to define it as a global variable?

When referencing the google map API documents, it is common practice to use script tags which make the google map instance a global variable. But is there a way to access the map instance without it being global? The npm/bower package angular-google-maps, ...

Leveraging both chained 'done' and 'then' for numerous asynchronous operations

Within my code, I have two functions containing ajax calls - setEmployees and getAllRecordsForEdit. I require certain code to execute after setEmployees completes, another set of code to run after both setEmployees and getAllRecordsForEdit finish, and addi ...

Guide on setting up a Redirect URL with React Router

I am aiming to trigger a redirect URL event using ReactJS. Is there a way to achieve this? I have already attempted the following: successRedirect(){ this.transitionTo('/'); } as well as successRedirect(){ this.router.transitionTo ...

Achieve the hidden div scroll effect in React by initially hiding the div and then allowing

I am currently working on a web chat application using next.js. One of the features is an emoji picker button that, when clicked, displays a menu of emojis. The issue I am facing is that in order for the user to see the emoji menu, they have to scroll down ...

Issue encountered while attempting to attach an event listener to an element within a class

Upon running the code, I encountered an error message that reads: Uncaught TypeError: this.startButton.addEventListener is not a function and I'm unsure of how to resolve it. Although I can successfully console.log the button inside the class, adding ...

Using Javascript/Ajax to manually delete an event handler from a Sys.EventHandlerList() can be achieved by following these

I have encountered a situation where I am working with two script controls, one containing the other. Successfully, I have managed to handle events from the child control on the parent using the following code snippet: initialize: function() { this._ ...

Control the data options available in the autosuggest textbox

I have implemented an autosuggest feature in a text box with predefined values. When typing the first letter in the textbox, a dropdown displays all related values. Is there a way to limit the number of displayed related values to 20? This is what my cu ...

Unraveling JSON data in AngularJS

After receiving a response from an OData service in JSON format, the data looks like this: [ { "id":1, "ProductName":"Surface Pro 2" }, { "id":2, "ProductName":"iPad" }, ] When att ...