gpt4 book ai didi

Javascript 数组到对象的转换

转载 作者:行者123 更新时间:2023-11-28 14:34:38 25 4
gpt4 key购买 nike

请建议我们如何将以下对象数组转换为使用 typescript/java 脚本指定的对象:

[
{
"name": "Alex",
"edu": [
{
"degree": "Grad",
"year": 2007
},
{
"degree": "Undergrad",
"year": 2005
}
]
},
{
"name": "Ali",
"edu": [
{
"degree": "Grad",
"year": 2010
},
{
"degree": "UnderGrad",
"year": 2008
}
]
},
{
"name": "Nik",
"edu": [
{
"degree": "Grad",
"year": 2009
},
{
"degree": "UnderGrad",
"year": 2007
}
]
}
]

致:

[   { name: "Alex", Grad: 2007, Undergrad: 2005 },
{ name: "Ali", Grad: 2010, Undergrad: 2008 },
{ name: "Nik", Grad: 2009, Undergrad: 2007 }

];

请帮助使用扩展运算符或任何其他运算符转换对象。谢谢!

最佳答案

您可以使用.map().reduce()方法:

let data = [{"name": "Alex","edu": [{"degree": "PhD","year": 2012},{"degree": "Grad","year": 2007},{"degree": "Undergrad","year": 2005}]},{"name": "Ali","edu": [{"degree": "Masters","year": 2012},{"degree": "Grad","year": 2010}]},{"name": "Nik","edu": [{"degree": "Masters","year": 2011},{"degree": "Grad","year": 2009}]}];

let result = data.map(
o => Object.assign(
{name: o['name']},
o['edu'].reduce((a, c) => (a[c['degree']] = c['year'], a), {})
)
);

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

关于Javascript 数组到对象的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com