Ways to avoid the overwriting of object properties

I am currently developing a function that generates a nested object with variable properties using the year and month as keys.

const sixMonthSummary = {};
// This function retrieves data for the most recent 6 months
for (let i = 0; i <= 6; i++) {
  const currentDate = new Date();
  const [, month, year] = new Date(
    currentDate.setMonth(currentDate.getMonth() - i)
  )

    .toLocaleDateString("en-SG")
    .split("/");

  sixMonthSummary[year] = {
    [month]: {
      rent: "",
      income: "",
      expenses: "",
    },
  };
}

console.log(sixMonthSummary)

The current output only shows the last and first index.

"2020": {
  "07": {
      "rent": "",
      "income": "",
      "expenses": ""
  }
},
"2021": {
  "01": {
      "rent": "",
      "income": "",
      "expenses": ""
  }
}

What adjustments can be made to ensure that all months are included in the data?

Answer №1

It is important to note that you are replacing the entire object key at

sixMonthSummary[year] = {}

Consider incorporating the existing object using a spread operator to preserve data from previous months.

const sixMonthSummary = {};
// This code snippet retrieves data for the most recent 6 months
for (let i = 0; i <= 6; i++) {
  const currentDate = new Date();
  const [, month, year] = new Date(
    currentDate.setMonth(currentDate.getMonth() - i)
  )

    .toLocaleDateString("en-SG")
    .split("/");

  sixMonthSummary[year] = {
    ...sixMonthSummary[year],
    [month]: {
      rent: "",
      income: "",
      expenses: "",
    },
  };
}

console.log(sixMonthSummary)

Answer №2

The reason the year key is being reset each time in the loop is because it is not being properly checked before assigning a new value. You can fix this by implementing a check like the following:

if(!sixMonthSummary[year]) {
 sixMonthSummary[year] = {};
}

sixMonthSummary[year][month] = {
 rent: "",
 income: "",
 expenses: "",
};

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

Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website. I would like it to detect when the URL changes using a HostListener. @HostListener('window:hashchange', ['$event']) onHashChange(event) { this.checkCu ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...

The TypeScript autocomplete feature is displaying two cars when I only need one

I am currently working with two props, one named car and the other named allStations. Whenever I press car, I am getting car.car as autocomplete, but I only want something like car.id, not car.car.id. Could someone please help me figure out what I am doi ...

When you sign up for a Selector subscription, you are met with nothing but

I am facing an issue with a selector that is passing data to a child component. Although the selector is functioning correctly and the child component is being constructed properly, I am encountering problems when trying to subscribe to the selector in the ...

How can one iterate through elements of a specified length using Jquery?

Currently, I am in the process of designing an animation for my website. The animation involves different divs that each contain an image and a description related to that image within an aside element. The width of the aside is slightly wider than the ima ...

Ways to display all image sources in React

I have an object containing product information, which includes answers with associated photos. I attempted to create a method that iterates through the images array and generates image tags with the source link, but for some reason, the images are not d ...

What is the best way to generate a circle around a specific point on the map without using a predetermined radius centered on a marker?

If I want to modify the code to respond to a click instead of creating a circle around a predefined marker, what changes can I make? Here is the code sample: https://developers.google.com/maps/documentation/javascript/examples/circle-simple <scri ...

Accessing the Node API with a GET request should be the first step taken before proceeding with

In my front-end setup, I have implemented an interceptor that automatically adds an Authorization header if a JWT token exists. There are 2 APIs in play: one for authorization checks and the other for handling data requests (the focus of my work). My goa ...

Demonstrating how to showcase information from an API array in a Node.js application and render it as a

I am aiming to showcase information retrieved from the API on my pug page, specifically displaying the names of car parks. Below is the code from Index.js var request = require('request'); var express = require('express'); var ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

The fetch function consistently executes the then() block, regardless of any errors, resulting in an undefined response

I'm encountering an issue where the catch block doesn't seem to be firing in my code, even though I am throwing a new error. However, the then block with an undefined response always fires. Can anyone help me understand why this is happening? Ca ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...

Avoid clicking on the HTML element based on the variable's current value

Within my component, I have a clickable div that triggers a function called todo when the div is clicked: <div @click="todo()"></div> In addition, there is a global variable in this component named price. I am looking to make the af ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

The mapStateToProps function in react-redux connect() is updating correctly, but the component is not re-rendering as

I am currently utilizing React, Redux, and the React-Redux Provider function. const mapStateToProps = (store: any) => { console.log("mapStateToProps", store.textTwo); return store.textTwo; }; If I apply the above mapStateToProps function to th ...

Access the contents of the selected cell in the MUI datagrid

When I choose a row from the datagrid, my attempt to access each cell value in that row always returns "undefined" when using selectedRowData.email. How can I correctly retrieve the data from a selected row's cells? <DataGrid checkboxSe ...

Why is the 'as' keyword important in TypeScript?

class Superhero { name: string = '' } const superheroesList: Superhero[] = []; const superheroesList2 = [] as Superhero[]; As I was exploring TypeScript, I stumbled upon these two distinct methods of declaring an array. This got me thinking w ...

What is the best way to set a JSON string as a variable?

I am attempting to send form input data to a REST service. Currently, the format is as follows: { "locationname":"test", "locationtype":"test", "address":"test" } However, the service is only accepting the following format: { "value": "{ loca ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...