开发者问题收集

TypeError:无法将未定义或空转换为对象:指出正确的方向

2022-04-26
555

我在网上找到了很多关于此问题和解决方案,但我还是有点新手,而且说实话我无法让它发挥作用。这可能很愚蠢,但是是的,我需要帮助:)

  • 错误:
TypeError: Cannot convert undefined or null to object
    at Function.assign (<anonymous>)
    at organizeCategoryData (C:\Users\alan_\Desktop\melonwallet\utils\records.js:59:35)
    at getRecords (C:\Users\alan_\Desktop\melonwallet\controllers\recordController.js:125:30)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
  • C:\Users\alan_\Desktop\melonwallet\utils\records.js:59:35
organizeCategoryData(categoryList, amountByCategory) {
    const categoryObject = Object.assign(    /// LINE 59
      ...categoryList.map(category => ({
        [category.name]: amountByCategory[category._id] || 0
      }))
    )
    categoryList.forEach(category => {
      category.amount = categoryObject[category.name]
    })
    return categoryObject
  }
  • (C:\Users\alan_\Desktop\ironhack\melonwallet\controllers\recordController.js:125:30)
const categoryObject = organizeCategoryData(   //// LINE 125
        categoryList,
        amountByCategory
      )

非常感谢!

/edit:忘记澄清这仅在我尝试使用之前创建的用户登录时发生。

2个回答

Object.assign 仅适用于对象。 ...categoryList.map(...) 是一个数组。要么将 Object.assign 放入映射中(或 forEach,因为它不返回任何内容)。或者查看 Object.fromEntries。

const categoryObject = {};
categoryList.forEach(category => 
  Object.assign(categoryObject, {
    [category.name]: amountByCategory[category._id] || 0
  })
);

// or 

const categoryObject = Object.fromEntries(
  categoryList.map(cat => ([cat.name, amountByCategory[cat._id] || 0]))
);
James
2022-04-26
organizeCategoryData(categoryList, amountByCategory) {
const cList = categoryList || []; //This will add a check for null and undefined
const categoryObject = Object.assign(    /// LINE 59
  ...cList.map(category => ({
    [category.name]: amountByCategory[category._id] || 0
  }))
)
cList.forEach(category => {
  category.amount = categoryObject[category.name]
})
return categoryObject

Zurez
2022-04-26