gpt4 book ai didi

javascript - ES6 : How do I unravel inner arrays and flatten the JSON array?

转载 作者:行者123 更新时间:2023-12-01 23:39:41 26 4
gpt4 key购买 nike

假设我有以下 JSON 数组:

[
{
"team": "Colts",
"players": [
{
"name": "Andrew Luck",
"position": "quarterback"
},
{
"name": "Quenton Nelson",
"position": "guard"
}
]
},
{
"team": "Patriots",
"players": [
{
"name": "Tom Brady",
"position": "quarterback"
},
{
"name": "Shaq Mason",
"position": "guard"
}
]
}
]

我想将 JSON 转换并扁平化为以下内容:

[
{
"name": "Andrew Luck",
"position": "quarterback",
"team": "Colts"
},
{
"name": "Quenton Nelson",
"position": "guard",
"team": "Colts"
},
{
"name": "Tom Brady",
"position": "quarterback",
"team": "Patriots"
},
{
"name": "Shaq Mason",
"position": "guard",
"team": "Patriots"
}
]

我如何使用 ES6 或 lodash 语法来做到这一点?

最佳答案

使用简单循环(ES2015):

const players = [];
for (const team of teams) {
for (const player of team.players) {
players.push(Object.assign({team: team.team}, player));
}
}

如果您的环境支持,您可以使用对象扩展来代替 Object.assign

Array#flatMap (将正式成为 ES2019 的一部分,或使用 lodash):

const players = teams.flatMap(
team => team.players.map(player => {...player, team: team.team})
);

关于javascript - ES6 : How do I unravel inner arrays and flatten the JSON array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423203/

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