作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有以下 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/
我是一名优秀的程序员,十分优秀!