首页 新闻 会员 周边 捐助

怎么把该数组快速处理成预期格式

0
悬赏园豆:5 [待解决问题]

[
{
"name": "432",
"fc_type": 0,
"key": "0"
},
{
"sub_type": 0,
"fc_type": 0,
"key": "0"
},
{
"code": "432",
"fc_type": 0,
"key": "0"
},
{
"model": "432",
"fc_type": 0,
"key": "0"
},
{
"throughput": 423,
"fc_type": 0,
"key": "0"
},
{
"name": "432",
"fc_type": 0,
"key": "1"
},
{
"sub_type": 0,
"fc_type": 0,
"key": "1"
},
{
"code": "432",
"fc_type": 0,
"key": "1"
},
{
"model": "432",
"fc_type": 0,
"key": "1"
},
{
"throughput": 432,
"fc_type": 0,
"key": "1"
}
]

预期效果
[
{
"name": "432",
"sub_type": 0,
"code": "432",
"model": "432",
"throughput": 423,
"fc_type": 0,
"key": "0"
},
{
"name": "432",
"sub_type": 0,
"code": "432",
"model": "432",
"throughput": 423,
"fc_type": 0,
"key": "1"
},
]

葫芦娃啊的主页 葫芦娃啊 | 初学一级 | 园豆:20
提问于:2022-04-15 19:20
< >
分享
所有回答(1)
0

reduce 方法

[
{
"name": "432",
"fc_type": 0,
"key": "0"
},
{
"sub_type": 0,
"fc_type": 0,
"key": "0"
},
{
"code": "432",
"fc_type": 0,
"key": "0"
},
{
"model": "432",
"fc_type": 0,
"key": "0"
},
{
"throughput": 423,
"fc_type": 0,
"key": "0"
},
{
"name": "432",
"fc_type": 0,
"key": "1"
},
{
"sub_type": 0,
"fc_type": 0,
"key": "1"
},
{
"code": "432",
"fc_type": 0,
"key": "1"
},
{
"model": "432",
"fc_type": 0,
"key": "1"
},
{
"throughput": 432,
"fc_type": 0,
"key": "1"
}
].reduce((prev, current) => {
  const obj = prev.find(item => item.key === current.key)
  if (obj) {
    //  结果数组中已经有这个 key 了就只添加属性
    Object.assign(obj, current)
  } else {
    prev.push(current)
  }
  return prev
}, [])
by.Genesis | 园豆:2824 (老鸟四级) | 2022-04-18 09:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册