Create a function called "insertEvent" that will insert a new event on a specified date

Below is the data structure for storing affairs according to years, months, and days:

let affairs = {
    2018: {
        11: {
            29: ['task111', 'task112', 'task113'],
            30: ['task121', 'task122', 'task123'],
        },
        12: {
            30: ['task211', 'task212', 'task213'],
            31: ['task221', 'task222', 'task223'],
        },
    },
    2019: {
        12: {
            29: ['task311', 'task312', 'task313'],
            30: ['task321', 'task322', 'task323'],
            31: ['task331', 'task332', 'task333'],
        }
    },
}

Create a function called addAffair that will add a new affair on a specified date.

Here is the incorrect solution:

addAffair(2020, 10, 21, 'affair111')
console.log(affairs)

function addAffair(year, month, day, affair){
  if(affairs[year]===undefined){
    affairs[year]={}
  }

  if(affairs[year][month]===undefined){
    affairs[month]={}
  }

  if(affairs[year][month][day]===undefined){
    affairs[day]=[]
  }

  affairs[year][month][day].push(affair)
}

The error displayed in the console is :

TypeError: Cannot read property '21' of undefined at addAffair (/script.js:36:26) at /script.js:24:1

Please assist in identifying the mistake.

Answer №1

As you embark on creating a new object, it's important to remember that you are not simply creating a sub-object of the year object. Instead, all your new objects should be at the same level, like this:

{
    2018: {}
    11: {}
    21: []
}

To properly nest your new object or array, ensure that you are creating them inside the previously created one.

addAffair(2020, 10, 21, 'affair111');
console.log(affairs);

function addAffair(year, month, day, affair){
  if(!affairs.hasOwnProperty(year)){
    affairs[year]={};
  }

  if(!affairs[year].hasOwnProperty(month)){
    affairs[year][month]={};
  }

  if(!affairs[year][month].hasOwnProperty(day)){
    affairs[year][month][day]=[];
  }

  affairs[year][month][day].push(affair);

}

An alternative approach is to use hasOwnProperty instead of === undefined. This small change can enhance the readability and understanding of your code.

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

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

Eliminating unnecessary gaps caused by CSS float properties

I need help figuring out how to eliminate the extra space above 'Smart Filter' in the div id='container_sidebar'. You can view an example of this issue on fiddle http://jsfiddle.net/XHPtc/ It seems that if I remove the float: right pro ...

The addition of meshes in real-time leads to a decrease in control responsiveness

I'm currently working on creating a 3D map using Three.js. My process involves building the geometry and texture with images of size 256x256 pixels, then constructing a THREE.Mesh to add to the scene upon completion. However, I've noticed that ...

How can I ensure that reactive form fields are properly validated in Angular2?

I am currently facing issues with validating Reactive form field in Angular 2. I have implemented a custom validator for this purpose, but it seems like my approach is not yielding accurate results as some of the test cases are failing. If anyone has insig ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

Detecting Image Loading with Javascript

My website is filled with numerous images categorized into 5 different groups, causing it to load slowly. To improve loading times, I have assigned each image a "data-src" attribute containing its actual source. Then, when a specific category is selected ...

Error message encountered: "Node.js Object [object Object] does not support the method"

My application uses Express.js and mongodb, including the mongodb Native driver. I have created a model with two functions for retrieving posts and comments: // Retrieve single Post exports.posts = function(id,callback){ MongoClient.connect(url, fun ...

Error: The post method in $setup is not defined in Vue Composition API

Dealing with a frustrating issue in my Vue application. One page is functioning perfectly fine, while the other is causing trouble by displaying this error: The first page loads a collection of wordpress posts (Blog.vue) without any issues, but the second ...

Steps for removing the console warning message: "The use of enableRowSelect has been deprecated. Instead, please utilize rowSelection."

) I have integrated React Data Grid from https://adazzle.github.io/react-data-grid/ multiple times in my application. One thing I noticed is that there is a console warning related to a prop called "enableRowSelect" which indicates whether the prop is bein ...

What steps can I take to troubleshoot the 'Uncaught DOMException: failed to execute add on DOMTokenList' error?

I am looking to create media icons <div class="contact"> <span> <i class="fa fa-phone"></i> </span> <span> <i class="fa fa-facebook"></i> </spa ...

What is the process to retrieve the username from my system and display it in a web browser?

Seeking assistance to retrieve my system's username and display it on a web browser. Currently, I have been using ActiveXObject method, which successfully retrieves the username, but has drawbacks such as requiring ActiveX to be enabled and only works ...

What is the best way to include a MongoDB match argument when it is received from the frontend, and to exclude it if it is not provided?

I'm currently working on creating an aggregation in MongoDB using NodeJS. The goal is to add an argument to the MongoDB match function if it exists when the resolver function is called. However, I'm encountering an issue where if no addition is m ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Obtain the accurate sequence of tr elements in the form of a jQuery object

Even though you can define tfoot before tbody in the source code, when displayed in the browser tfoot will still appear last: <table> <thead><tr><th>i get displayed first</th></tr></thead> <tfoot><t ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

Getting Started with Parsing JSON Objects in ReactJS

In my ReactJS project, I am trying to parse through a JSON list using the following model: public class ModelEmployee { public List<Employeelist> Employees { get; set; } public int count { get; set; } public int Pagenumber { get; set; } ...

Did you receive an incorrect solution for the inverse permutation problem on Codesignal?

Currently tackling the inversePermutation challenge on codesignal. Here's a quick summary of the task: Given a permutation, create its inverse permutation. For example, if permutation = [1, 3, 4, 2], then the output should be: inversePermutation(per ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...