我有一个要映射的对象数组,如下所示:
Array (3)
0 {_id: "5fea07cd143fd50008ae1ab2", newBalance: 1500, balanceDate: "2020-12-28T16:29:00.391Z"}
1 {_id:"5fea0837b2a0530009f3886f", newBalance: 1115, balanceDate: "2020-12-28T16:30:45.217Z"}
2 {_id: "5fec30faef904e0dd1e39c60", newBalance: 1415, balanceDate: "2020-12-30T07:49:13.214Z"}我用来映射的函数如下所示:
{ debtBalance.map ((debt, index) => {
return (
<div className="transaction-history">
<div className="transaction-history-entry" key={index}>
<p><Moment date={debt.balanceDate} format="Do MMM" /></p>
<p>-£{debt.newBalance}</p>
</div>
</div>
)
})
}我想修改我的映射函数,以减少这些对象中的“newBalance”条目--然后将当前值与之前的值进行比较,并找出两者之间的差异。
我想应该是这样的……
debt.reduce((previousValue, currentValue) => {
return previousValue.newBalance - currentValue.newBalance
})但是我得到了'debt.reduce是未定义的‘。
一旦我设置了reduce函数,我只想在我的应用程序中呈现不同之处,但这将是简单的。
如果您有任何建议,我们将不胜感激!:)
发布于 2020-12-30 17:13:14
您可以使用Array.map或Array.reduce。
const debtBalance = [
{
_id: '5fea07cd143fd50008ae1ab2',
newBalance: 1500,
balanceDate: '2020-12-28T16:29:00.391Z'
},
{
_id: '5fea0837b2a0530009f3886f',
newBalance: 1115,
balanceDate: '2020-12-28T16:30:45.217Z'
},
{
_id: '5fec30faef904e0dd1e39c60',
newBalance: 1415,
balanceDate: '2020-12-30T07:49:13.214Z'
}
];
// Using Array.map
const diffs1 = debtBalance.map((item, index) =>
index === 0 ? 0 : debtBalance[index - 1].newBalance - item.newBalance
);
console.log(diffs1);
// Using Array.reduce
const diffs2 = debtBalance
.map(item => item.newBalance)
.reduce(
(val, cur, index, original) => [
...val,
index === 0 ? 0 : original[index - 1] - original[index]
],
[]
);
console.log(diffs2);
发布于 2020-12-30 17:07:31
不要为此使用reduce,它不适用于这种类型的转换。没有什么可以累加的,你所要做的就是回顾一个数组元素并计算一些东西。对于每个数组元素,这是相同的过程,因此.map是正确的选择。
const balances = [
{_id: "5fea07cd143fd50008ae1ab2", newBalance: 1500, balanceDate: "2020-12-28T16:29:00.391Z"},
{_id:"5fea0837b2a0530009f3886f", newBalance: 1115, balanceDate: "2020-12-28T16:30:45.217Z"},
{_id: "5fec30faef904e0dd1e39c60", newBalance: 1415, balanceDate: "2020-12-30T07:49:13.214Z"}
];
balances.map(
(balance, index) => ({
...balance,
difference: index >= 1 ? (balances[index - 1].newBalance - balance.newBalance) : 0
})
);发布于 2020-12-30 16:59:12
你可以在渲染过程中直接减少,但提前准备数据可能会更简单,
以下是如何使用reduce进行映射的示例:
var data = [
{_id: "5fea07cd143fd50008ae1ab2", newBalance: 1500, balanceDate: "2020-12-28T16:29:00.391Z"},
{_id:"5fea0837b2a0530009f3886f", newBalance: 1115, balanceDate: "2020-12-28T16:30:45.217Z"},
{_id: "5fec30faef904e0dd1e39c60", newBalance: 1415, balanceDate: "2020-12-30T07:49:13.214Z"}
]
var res = data.reduce((ac, item) => {
var previous = ac.length && ac[ac.length - 1]
var diff = previous && previous.newBalance - item.newBalance
var augmented = item
augmented.diff = diff
return [ // we'll output an array, because that's what you'll need later
...ac, // you push in previous results
augmented
]
}, [])
console.log('res', res)
https://stackoverflow.com/questions/65504067
复制相似问题