Javascript - 将新对象添加到对象数组中

Javascript - Add new object into array of objects

请。我有一个未婚夫余额的周期。它是一个对象数组,例如:

export const balances = [
type: types.outgoing,
    date: 20220410,
    amount: 282.12,
    category: categories.installments,
    source: 'Debit account',
    destination: 'Leasing company',
  },
  {
    type: types.income,
    date: 20220413,
    amount: 1385.3,
    category: categories.job,
    source: 'My employeer',
    destination: 'Debit account',
  },
  ...
]

等...

如您所见,我有一个 类别 ,这意味着我在 balances 中循环每个交易,我必须为每个交易创建单独的类别每个类别的总金额,类别中的项目数量以及每个类别的详细交易。我正在使用 array.forEach() 周期:

balances.forEach((balance) => {

  // Checking if category already exists in my array of categories
  let categoryIndex = categories.findIndex((category) => category.category === balance.category)

  // Create details of transaction
  let transactionDetail = {
    date: balance.date,
    amount: balance.amount,
    source: balance.source,
    destination: balance.destination,
  }

  // If category already exists, just calculate total and add new object into array details
  if (categoryIndex !== -1) {
    console.log([categories[categoryIndex].details])
    categories[categoryIndex] = {
      type: balance.type,
      category: balance.category,
      amount: categories[categoryIndex].amount + balance.amount,
      count: (categories[categoryIndex].count += 1),

      // This row is wrong. I cannot use this
      details: [categories[categoryIndex].details].push(transactionDetail),
    }
  } else {
    // If category doesn't yet exists, we must create a first values in this category
    categories.push({
      type: balance.type,
      category: balance.category,
      amount: balance.amount,
      count: 1,
      details: [transactionDetail],
    })
  }
}

但是行

details: [categories[categoryIndex].details].push(transactionDetail)

无法正常工作。可能的原因是,我有时 Object as tyopeof 结果有时 undefined

console.log([categories[categoryIndex].details])有时输出:

// Output for
// console.log([categories[categoryIndex].details])
[Array(1)]0: Array(1)
0: {date: 20220414, amount: 410, source: 'xxx', destination: 'yyy'}
length: 1[[Prototype]]: 
Array(0)length: 1
[[Prototype]]: Array(0)

[2]
0: 2
length: 1
[[Prototype]]: Array(0)

知道如何将对象 transactionDetail 添加为现有数组中的下一个对象吗?非常感谢您的任何建议。

我不明白。如果类别已经存在,我可以连接字符串,添加数字,但我不能将下一个对象添加到对象数组中。

编辑:刚刚在解释中将 transaction 更改为 trasactionDetail

我在你后面的版块中发现了几个错误并已更正;让我解释一下我所做的更改。

  1. 在您标记为错误的行中,您出于某种原因将值放在括号中。 Categories.details大概是一个TransactionDetail的数组,所以这里就不用再嵌套了。然而,如果你推入一个数组,returns 包含数组中的对象数量,那么当你在该行中执行此操作时,details 最终将始终填充一个数字。相反,在我的版本中,我将您通过索引提取的现有类别拆分为 existing,然后将值简单地推入其 details 数组。这也只是清理了你的条件的上半部分,因为你只需要引用现有对象的属性来以更清晰的方式匹配新值。

  2. 您正在使用 1(categories[categoryIndex].count += 1) 来增加计数。但是,您也在此处精确设置该对象,因此这不是一个好的做法。相反,设置您打算在此处使用的值并将其全部提交到 categories 数组作为一件事,而不是此处设置的某些值不匹配,有些设置不同。我将其更正为 existing.count + 1.

这是您更新后的完整代码:

balances.forEach((balance) => {

  // Checking if category already exists in my array of categories
  let categoryIndex = categories.findIndex(category => category.category === balance.category);

  // Create details of transaction
  let transactionDetail = {
    date: balance.date,
    amount: balance.amount,
    source: balance.source,
    destination: balance.destination,
  };

  // If category already exists, just calculate total and add new object into array details
  if (categoryIndex !== -1) {
    const existing = categories[categoryIndex];
    existing.details.push(transactionDetail);

    categories[categoryIndex] = {
      type: balance.type,
      category: balance.category,
      amount: existing.amount + balance.amount,
      count: existing.count + 1,
      details: existing.details
    };
  } else {
    // If category doesn't yet exists, we must create a first values in this category
    categories.push({
      type: balance.type,
      category: balance.category,
      amount: balance.amount,
      count: 1,
      details: [transactionDetail],
    });
  }
});