将键值选项卡转换为键值数组

Transform an tab of key values into an array of key values

我想将键值的选项卡数组转换为键值数组

     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};
},{})

试试这个

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

看起来 reduce 是更适合您的情况的方法,因为您想从数组中创建一个对象。

类似

 rates.reduce((ratesObj, rate) => {
   ratesObj[rate] = account.vent.find(v => v.rate === rate)?.vat;
   return ratesObj;
 }, {})