我有以下架构:const SubmitDebtSchema = new Schema ({ balance: [{ balanceDate: Date, newBalance: Number }],});我试图遍历我的数据库条目,从余额数组中的每个对象中拉出“newBalance”,然后将它们归约/求和。但是,它正在返回“NaN”——我不明白为什么。这是我获取数据的 Axios 调用: componentDidMount() { axios.get("/api/fetch/fetchDebtCards") .then((response) => { this.setState({ debts: response.data }) console.log(this.state.debts.balance.newBalance) }) }那里的控制台日志成功检索了数据库条目。这是我的减少功能:const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) { return ( previousValue + currentValue.balance.newBalance ) }, 0)您可以看到,我正在尝试利用“balance.newBalance”来访问每个余额对象中的 newBalance。谁能指出我做错了什么?编辑:我的控制台日志,有两个条目。我想要做的是从中获取 newBalance array.length -1,然后通过减少将它们加在一起。[日志]数组0 对象余额:[{_id:“5fbbddd1077c56000828973c”,balanceDate:“2020-11-23T16:05:36.124Z”,newBalance:400}]1 对象余额:[{_id: "5fbc06f58b2f98000865df54", balanceDate: "2020-11-23T19:01:07.789Z", newBalance: 300}] (1)
1 回答

湖上湖
TA贡献2003条经验 获得超2个赞
如果“console.log(this.state.debts.balance.newBalance)”有效,则债务不是数组,那么您如何在债务上使用地图?Map 只能用于数组。
我不确定您的债务对象/数组到底是怎样的。也许它的日志会有所帮助。
如果它是一个数组,那么这可能会起作用。
const sumBalance = this.state.debts.map(x => x.balance).flat().reduce((a,b) => a + b.newBalance, 0)
而如果它是一个对象,那么这可能会起作用
const sumBalance = this.state.debts.balance.reduce((a,b) => a+b.newBalance, 0)
如果这些都不起作用,只需记录“this.state.debts”,让我们看看你有什么。
编辑:好的,所以你只需要余额数组的最后一个值(最新余额),像这样?
const sumBalance = this.state.debts.map(x => x.balance[x.balance.length-1].newBalance).reduce((a,b) => a + b, 0)
添加回答
举报
0/150
提交
取消