重新排列JavaScript数组

georgespatton2

如何以上述格式重新排列数据。我必须重新格式化数组并制作新的数组:

[
   {
      "cost":"1.3947648891000006",
      "start_date":"2020-06-10",
      "account":"1"
   },
   {
      "cost":"1.4069091170999999",
      "start_date":"2020-06-11",
      "account":"1"
   },
   {
      "cost":"1.401164025099997",
      "start_date":"2020-06-11",
      "account":"2"
   },
   {
      "cost":"2.50928182113",
      "start_date":"2020-06-12",
      "account":"2"
   }
]

至:

[
   {
      "start_date":"2020-06-10",
      "account_1_cost":"1.3947648891000006"
   },
   {
      "start_date":"2020-06-11",
      "account_1_cost":"1.4069091170999999",
      "account_2_cost":"1.401164025099997"
   },
   {
      "start_date":"2020-06-12",
      "account_2_cost":"2.50928182113"
   }
]

我尝试过reduce函数和map函数都没有用。

乔乔先生

只需使用array.reduce

const arr = 
  [ { cost: '1.3947648891000006', start_date: '2020-06-10', account: '1' } 
  , { cost: '1.4069091170999999', start_date: '2020-06-11', account: '1' } 
  , { cost: '1.401164025099997',  start_date: '2020-06-11', account: '2' } 
  , { cost: '2.50928182113',      start_date: '2020-06-12', account: '2' } 
  ] 

const res = 
  arr.reduce((acc,{cost, start_date, account})=>
    {
    let el = acc.find(x=>x.start_date===start_date)
    if (!el) acc.push(el = { start_date })
    el[`account_${account}_cost`] = cost
    return acc
    },[])

console.log( res ) 
.as-console-wrapper { max-height: 100% !important; top: 0; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章