如何在Javascript中更改此类型的结构
很抱歉,我不会说英语,我是javascript的初学者,我有一个问题 我有这个:如何在Javascript中更改此类型的结构,javascript,arrays,Javascript,Arrays,很抱歉,我不会说英语,我是javascript的初学者,我有一个问题 我有这个: [ { nombre: "Juan", edad: 23, type: "seccion" }, { nombre: "Miguel", edad: 30, typo: "e" }, {
[
{
nombre: "Juan",
edad: 23,
type: "seccion"
},
{
nombre: "Miguel",
edad: 30,
typo: "e"
},
{
nombre: "Claudio",
edad: 22,
type: "b"
},
{
nombre: "Antonio",
edad: 33,
type: "seccion"
},
{
nombre: "Angela",
edad: 44,
type: "rr"
},
{
nombre: "Norberto",
edad: 27,
type: "xx"
} ]
我希望:
[
{
nombre: "Juan",
edad: 23,
type: "section",
items: [
{
nombre: "Miguel",
edar: 30,
typo: "e"
},
{
nombre: "Claudio",
edar: 22,
typo: "bbbb"
},
]
},
{
nombre: "Antonio",
edad: 33,
type: "section",
items:[
{
nombre: "Angela",
edar: 44,
typo: "rr"
},
{
nombre: "Norberto",
edar: 27,
typo: "xx"
}
]
}
]
如您所见,我需要在值等于“section”的元素中对没有type属性值为“section”的对象类型元素进行分组
原始数组中存在一些差异,例如,键入
->类型
,seccion
->部分
我假设这些都是打字错误,并且只使用类型
和部分
来保持一致性,否则它将不起作用
const数据=[
{
名字:“胡安”,
edad:23,
类型:“节”
},
{
名字:“米格尔”,
edad:30,
类型:“e”
},
{
绰号:“克劳迪奥”,
edad:22,
类型:“b”
},
{
绰号:“安东尼奥”,
edad:33,
类型:“节”
},
{
名字:“安吉拉”,
edad:44,
类型:“rr”
},
{
名字:“诺贝托”,
edad:27,
类型:“xx”
}
];
常量结果=数据减少((acc,cur)=>{
if(cur.type==='section'){
acc.push({…cur,items:[]});
}否则{
acc[acc.length-1]。项目推送(cur)
}
返回acc;
}, []);
控制台日志(结果)代码>什么决定了非节元素进入哪个节元素?为什么米格尔和克鲁亚迪奥要进入胡安区而不是安东尼奥区?正常的做法是在提问之前尝试自己解决问题。见和。谢谢对不起,问题的最后是澄清。至于测试,它们纯粹是垃圾,我离解决方案太远了,所以我没有穿上它们,简言之,它们没有带来任何东西:(