这就是我掌握的数据

StudentInfo:[
          {
           name:'Rajesh',
              courseDetails:{
               //some info
              }
          },
          {
           name:'Amit',
              courseDetails:{
               //some info
              }
           },
          {
           name:'Rajesh',
              Address:[
               //some info
              ]
          }

]

从上面的数据中,我如何使用Java脚本合并具有相同关键字的数据?

这是我希望看到的最终结果

StudentInfo:[
          {
           name:'Rajesh',
              courseDetails:{
               //some info
              }
              Address:[
               //some info
              ]
          }
]

推荐答案

you can use reduce along with rest parameters.
group by name and then take the values array using Object.values

const StudentInfo =[
          {
           name:'Rajesh',
              courseDetails:{
               //some info
              }
          },
          {
           name:'Amit',
              courseDetails:{
               //some info
              }
           },
          {
           name:'Rajesh',
              Address:[
               //some info
              ]
          }

]

const res = Object.values(StudentInfo.reduce((acc,{name,...rest}) => {
  acc[name]??={name}
  acc[name] = {...acc[name],...rest}
  return acc
},{}))

console.log(res)

一个班轮

const StudentInfo =[          {          name:'Rajesh',              courseDetails:{                     }          },          {           name:'Amit',              courseDetails:{              }           },          {           name:'Rajesh',              Address:[              ]          }]

const res = Object.values(StudentInfo.reduce((acc, { name, ...rest }) => ({...acc,[name]: { ...(acc[name] || {}), name, ...rest }}), {}));

console.log(res)

Javascript相关问答推荐

原型链中的同一财产怎么会有不同的价值?

我可以后增量超过1(最好是内联)吗?

橡皮擦完全让画布变成白色

脚本.js:3:20未捕获的类型错误:无法读取空的属性(读取addEventHandler)

fetch在本地设置相同来源的cookie,但部署时相同的代码不会设置cookie

JavaScript文本区域阻止KeyDown/KeyUp事件本身上的Alt GR +键组合

一次仅播放一个音频

成帧器运动中的运动组件为何以收件箱开始?

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

是什么原因导致此Angular 16应用程序中类型错误时属性结果不存在?

如何在RTK上设置轮询,每24小时

docx.js:如何在客户端使用文档修补程序

Angular material 拖放堆叠的牌副,悬停时自动展开&

如何使覆盖div与可水平滚动的父div相关?

在网页上添加谷歌亵渎词

如何调用名称在字符串中的实例方法?

Angular 中的类型错误上不存在获取属性

向数组中的对象添加键而不改变原始变量

每次重新呈现时调用useState initialValue函数

Phaser3 preFX addGlow不支持zoom