我想将键值的制表符数组转换为键值数组
rates.map(rate => {
return {
[rate]: account.vent.filter(v => v.rate === rate)[0]
?.vat,
}
})
(5) [{…}, {…}, {…}, {…}, {…}]
0: {10: 500}
1: {20: 630}
2: {5: undefined}
3: {19.6: undefined}
4: {1: undefined}
我的控制台上有这个,我想要更像:
{
10: 500
20: 630
5: undefined
19.6: undefined
1: undefined
}
加上这个,你的问题就解决了
.reduce(function(p,c){
return {...p,...c};
},{})
添加上面的代码
后,您的代码将看起来像这样rates.map(rate => {
return {
[rate]: account.vent.filter(v => v.rate === rate)[0]
?.vat,
}
})
.reduce(function(p,c){
return {...p,...c};
},{})
看起来reduce是一个更适合你的方法,因为你想从一个数组中创建一个对象。
之类的rates.reduce((ratesObj, rate) => {
ratesObj[rate] = account.vent.find(v => v.rate === rate)?.vat;
return ratesObj;
}, {})
试试这个
array.reduce((acc, item)=>{
return {...acc, ...item}
},{})
减少方法:-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
一个关于reduce方法的好视频:-https://www.youtube.com/watch?v=IfieE2G3bfg