Need Help with creating dynamic object in react

Need Help with creating dynamic object in react
0

#1

Hi,

I am working on one of my side projects , a simple expense tracker with an option of a calendar control and two buttons for adding income and expense. I am using React

for this. Working Code Pen here: https://codepen.io/bansal/pen/GyqBPd

I thought of state structure to be something like this:


state=
{
records:
{
   2017:{11:{income:12000,expense:3000},10:{income:5000, expense:200}}
   2016:{11:{income:12000,expense:3000}}
}
};

records =>followed by year=>months=actual data
I am calling addIncome and addExpense methods to add the expense and income and they are working fine for me. As both of the methods work in a similar way so I created a function updateState to update the respective state for expense or income.

I need help in line no 115 :

if (key == "expense")
       updatedRecordsForSelectedYear = {
         ...recordsForSelectedYear,
         [selectedMonth]: { expense: parseInt(amount, 10) }
       };
     else
       updatedRecordsForSelectedYear = {
         ...recordsForSelectedYear,
         [selectedMonth]: { income: parseInt(amount, 10) }
       };```
Here I have to write if-else block just to create the object expense and income, I want to skip this check, I want to supply direct key here. How can I achieve that? If I pass key , the state is updated with string key and not the actual expense or income.

I have tried following code:
  1. updatedRecordsForSelectedYear = {
    …recordsForSelectedYear,
    [selectedMonth]: { ${key}: parseInt(amount, 10) }
  2. updatedRecordsForSelectedYear = {
    …recordsForSelectedYear,
    [selectedMonth]: { key: parseInt(amount, 10) }

None of them works for me. I would be highly obliged if someone helps. Thanks.

#2

To use variables in an objects wrap it inside squares, (like you already did for selectedMonth for example.

So this should be fine (assuming key is a variable you are passing to the method):

updatedRecordsForSelectedYear = {
…recordsForSelectedYear,
[selectedMonth]: { [key]: parseInt(amount, 10) }

Have you tried this?


#3

thanks @Marmiz!! This solves it . Thanks so much… I missed that…


#4

Sometimes we get so distracted in the bigger pictures that we loose focus on the small details.

Glad I could have been of help, and happy coding :slight_smile:


#5

Yup, exactly as you said :slight_smile: