Retrieving an array from a JSON data structure

I encountered a JSON object like this:

var Events = {
    "Jan" : [],
    "Feb" : [],
    "Mar" : {
        "23" : [
            {"eventName" : "Start", "eventYear" : 2015, "eventDescription" : "First event description"},
            {"eventName" : "Start 2", "eventYear" : 2016, "eventDescription" : "Second event description"},
            {"eventName" : "Start 3", "eventYear" : 2017, "eventDescription" : "Third event description"}
        ],
        "24" : [
            {"eventName" : "Start", "eventYear" : 2015, "eventDescription" : "First event description for 24"},
            {"eventName" : "Start 2", "eventYear" : 2016, "eventDescription" : "Second event description for 24"}
        ]
    },
    "Apr" : [],
    "May" : [],
    "Jun" : [],
    "Jul" : [],
    "Aug" : [],
    "Sep" : [],
    "Oct" : [],
    "Nov" : [],
    "Dec" : []
}

I'm attempting to extract the events array for the current month:

window.addEventListener('DOMContentLoaded', init);
var date, month_names_short, thisMonthEvents;
function init(){
    date = new Date();
    month_names_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    thisMonthEvents = Events.month_names_short[date.getMonth()];
};

However, I'm encountering an error message

TypeError: Cannot read property '2' of undefined
on this line of code:

thisMonthEvents = Events.month_names_short[date.getMonth()];

Could someone please point out what mistake I am making and provide a solution? Thank you.

Answer №1

To begin, locate the month name within the month_names_short array based on its index. Then, using bracket notation and the retrieved name, you can access the corresponding event:

function initialize() {
    currentDate = new Date();
    month_names_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    thisMonthEvents = Events[month_names_short[currentDate.getMonth()]];
};

Answer №2

If you are considering utilizing the array containing abbreviated month names, here is one way to achieve that:

function initialize(){
    currentDate = new Date();
    monthNamesShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    for (var idx in monthNamesShort) {
         var currentMonth = monthNamesShort[idx];
         thisMonthsEvents = Events[currentMonth];
    }
};

Answer №3

Replace "." with "[]" donation.

window.addEventListener('DOMContentLoaded', initialize);
var currentDate, shortMonthNames, currentMonthEvents;
function initialize(){
    currentDate = new Date();
    shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    currentMonthEvents = Events[shortMonthNames[currentDate.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

One controller displays ng-repeats while the other does not

I have 2 controllers loading in different locations within my view. One controller works perfectly, but the other one does not show ng-repeats or appear in ng-inspector. I have confirmed that the http data is visible in the inspector. Both controllers are ...

Change a JSON object with multiple lines into a dictionary in Python

I currently have a file containing data in the form of multiple JSON rows. Although it consists of about 13k rows, below is a shortened example: {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} Here i ...

What determines the priority of execution in the execution context stack?

Check out this insightful tutorial on execution context in JavaScript here. It's interesting how the order of invoking functionA() and console.log("GlobalContext") differs in terms of writing code versus the execution context stack. I'm curious, ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Save Bson query as a Javascript log

When working with Java to create a complex MongoDB query, I often log the query before executing it: log.info("Filter: {}", queryFilter); The logged query output typically looks like this: And Filter{filters=[Filter{fieldName='FinInstrmGnlAttrbts.C ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

Selecting a dropdown value dynamically after a form submission in ColdFusion using jQuery

I created a basic form with the use of an onload function to populate market values by default. However, I encountered an issue where after selecting a market value from the drop-down list and submitting the form, the selected value does not stay selected ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

Is it feasible to add a row in bold font following every set of 10 rows written in regular text?

Looking for a way to implement pagination on a table with dynamic headers? I am using rows with font-weight:bold to act as headers for the pagination. Is it possible to insert a row with font-weight:bold every 10 rows? I am unsure of how to achieve this, ...

Is it possible to customize the Maki icon color on mapbox?

I've been racking my brain trying to figure out how to dynamically add color to Mapbox's maki icons using plain Javascript. The documentation offers solutions using deprecated tools like tilemill or CSS, but my icons are generated on-the-fly from ...

Utilizing jQuery to toggle containers based on link clicks

Hello everyone, I'm having trouble getting this code to work. I have a set of 4 links and I need to display one div container for 3 of them, and another for the remaining 1 link, switching back and forth. Any suggestions? <div class="content activ ...

Enhancing Android app efficiency by improving performance in accessing Json file data from various classes

As I delve into utilizing Json files for my app, the question arises regarding the most efficient method to store and access this data across multiple classes. Currently, I am working with a Json file containing various currency conversion rates. The chal ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

unable to decode JSON into a structure

After receiving an attribute in JSON format from a REST service and capturing it with an invokeHTTP processor, I am looking to incorporate it into a JSON content flow using the JOLT processor. My existing content looks like this: { "id": 123, "use ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Trouble encountered when transmitting JavaScript array through AJAX to Laravel

I am encountering an issue with sending a JavaScript array to a controller via an AJAX GET method. Here is the structure of my JavaScript: var requestData = JSON.stringify(commentsArray); console.log(requestData); //I can see the correct JSO ...

The i18n feature in node.js seems to be malfunctioning as the setLocale function is not working properly. Regardless

Something seems off with my usage of the i18n library, but I believe I'm following the correct steps. I've been attempting to switch the locale. Here's my current code. Despite calling setLocale on the global i81n variable, it continues to ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...