无法弄清楚如何正确断言一个对象

时间:2018-10-07 09:10:57

标签: javascript object mutation

let records = {
  2018: {
    Jan: {
      records: [{ 
        id: 123, 
        date: '01-Jan-2018', 
        amount: 300,
        type: 'expense'
       }],
      totalExpenses: 300,
      totalIncome: 0
    },
    Feb: {
      records: [{ 
        id: 234, 
        date: '01-Jan-2019', 
        description: 'Syabas', 
        amount: 100,
        type: 'income'
       }],
      totalExpenses: 0,
      totalIncome: 100
    }
  },
  2019: {
    Jan: {
      records: [{ 
        id: 789, 
        date: '01-Jan-2019', 
        description: 'McD', 
        amount: 150,
        type: 'expense'
       }],
      totalExpenses: 150,
      totalIncome: 0
    },
  }
}
let year = 2018;
let month = 'Jan';

const yearRecords = records[year] || { [year]: {} };
const monthRecords = yearRecords[month] || { [month]: {} };
const recordList = monthRecords['records'] || [];

const newRec = {id: 666, amount: 9999};
const newRecordList = [...recordList, newRec];
monthRecords['records'] = newRecordList;
monthRecords.totalExpenses = newRecordList.reduce((accumulator, record) => {
  return accumulator + record.amount;
}, 0);


console.log({...records, [year]: yearRecords})

我有一个现有records的列表,我正在尝试将新记录newRec附加到此records中。

挑战是,年份的关键可能/可能不存在,同样要持续几个月。如果存在,则追加到records数组中并增加totalExpenses字段。

如上所示,如果year/month中存在records,我就可以使用它,但是如果我将其设置为let year = 2020,它在记录中会额外增加一级,这是错误的。我已经尝试了许多小时仍无法弄清楚,想知道是否有更简单的方法来进行上述断言?

当年份= 2020年时,以下显示错误的结果

let records = {
      2018: {
        Jan: {
          records: [{ 
            id: 123, 
            date: '01-Jan-2018', 
            amount: 300,
            type: 'expense'
           }],
          totalExpenses: 300,
          totalIncome: 0
        },
        Feb: {
          records: [{ 
            id: 234, 
            date: '01-Jan-2019', 
            description: 'Syabas', 
            amount: 100,
            type: 'income'
           }],
          totalExpenses: 0,
          totalIncome: 100
        }
      },
      2019: {
        Jan: {
          records: [{ 
            id: 789, 
            date: '01-Jan-2019', 
            description: 'McD', 
            amount: 150,
            type: 'expense'
           }],
          totalExpenses: 150,
          totalIncome: 0
        },
      }
    }
    let year = 2020;
    let month = 'Jan';

    const yearRecords = records[year] || { [year]: {} };
    const monthRecords = yearRecords[month] || { [month]: {} };
    const recordList = monthRecords['records'] || [];

    const newRec = {id: 666, amount: 9999};
    const newRecordList = [...recordList, newRec];
    monthRecords['records'] = newRecordList;
    monthRecords.totalExpenses = newRecordList.reduce((accumulator, record) => {
      return accumulator + record.amount;
    }, 0);


    console.log({...records, [year]: yearRecords})

1 个答案:

答案 0 :(得分:1)

您可以使用python manage.py makemigrations python manage.py migrate 方法执行此操作。

reduce