如何将对象的结构转换为另一个结构?JavaScript

如何将对象的结构转换为另一个结构?JavaScript,javascript,Javascript,我有JS对象的这种结构: const obj1 = { "groups": [ { "name": "test", "type": "app" }, { "name": "test2", "type": "app" }, { "name": "test1", "type": "app2

我有JS对象的这种结构:

 const obj1 = {
      "groups": [
        {
          "name": "test",
          "type": "app"
        },
        {
          "name": "test2",
          "type": "app"
        },
        {
          "name": "test1",
          "type": "app2"
        },
        {
          "name": "test3",
          "type": "app2"
        }
      ]
    }
我需要最终得到这个: 结果:


可能是ES6+aproach或更早的版本

这归结为只需迭代
obj1。组
建立一个新的输出对象:

const obj1={
“团体”:[
{“name”:“test”,“type”:“app”},
{“name”:“test2”,“type”:“app”},
{“name”:“test1”,“type”:“app2”},
{“name”:“test3”,“type”:“app2”}
]
};
const out={};
对于(让obj1.groups的组){
out[group.type]=out[group.type]| |{groups:[]};
out[group.type].groups.push({name:group.name});
}

控制台。注销您可以使用以下命令简洁地执行此操作:

const obj1={
“组”:[{“名称”:“测试”,“类型”:“应用”},{“名称”:“测试2”,“类型”:“应用”},{“名称”:“测试1”,“类型”:“应用2”},{“名称”:“测试3”,“类型”:“应用2”}]
};
const result=obj1.groups.reduce((obj,{name,type})=>{
返回(obj[type].groups.push({name}),obj);
},{app:{groups:[]},app2:{groups:[]});

控制台日志(结果)
如果你只是将
变异出来
,那么在这里使用
reduce
有什么好处?如果您使用一个简单的
for…of
循环编写它,代码甚至会更短。@Bergi个人认为作为
reduce
更容易阅读。你是对的,一个关于。。。of
在这里也同样适用,只需进行最小的更改
 const obj1 = {
      app: {groups: [{name: 'test'},{name: 'test2'}]},
      app2: {groups: [{name: 'test1'},{name: 'test3'}]},
    }