我在映射 JS 对象并将数据从一个参数合并到另一个参数的子对象中时遇到困难。
假设我有以下 JSON:
const data = [
{
"difficulty": "Easy",
"levels": [
{
"id": 0,
"title": "Training",
"description": "First training level."
},
{
"id": 1,
"title": "Story",
"description": "First story level."
}
]
},
{
"difficulty": "Medium",
"levels": [
{
"id": 2,
"title": "Training",
"description": "First training level at medium difficulty."
}
]
}
];
我想操纵它返回:
[
{
"id": 0,
"title": "Training",
"description": "First training level.",
"difficulty": "Easy"
},
{
"id": 1,
"title": "Story",
"description": "First story level.",
"difficulty": "Easy"
},
{
"id": 2,
"title": "Training",
"description": "First training level at medium difficulty.",
"difficulty": "Medium"
}
];
我已经尝试过:
const result = data.map(item => {
const { difficulty, levels } = item;
return levels.map(level => ({ ...level, difficulty }));
});
但我最终得到:
[
[
{
"id": 0,
"title": "Training",
"description": "First training level.",
"difficulty": "Easy"
},
{
"id": 1,
"title": "Story",
"description": "First story level.",
"difficulty": "Easy"
}
],
[
{
"id": 2,
"title": "Training",
"description": "First training level at medium difficulty.",
"difficulty": "Medium"
}
]
]
我只想返回添加了难度
的所有级别
。
最佳答案
发生这种情况是因为您使用嵌套的 .map 函数。每个 .map 函数都会返回一个数组。为了避免这种情况,您可以使用 .flat() 方法来减少嵌套 你的解决方案可以改成这样
const result = data.map(item => {
const { difficulty, levels } = item;
return levels.map(level => ({ ...level, difficulty }));
}).flat();
默认情况下,它会压缩 1 个嵌套数组。 您可以在这里找到更多信息:Array.prototype.flat()
但要小心地将其用于大量数据集合,因为它会迭代数组,因此会降低性能。
UPD 没有 .map 方法的解决方案
function mapDifficultyToLevels(data) {
const result = []
data.forEach(item => {
item.levels.forEach(level => {
result.push({
difficulty: item.difficulty,
...level
})
})
})
return result
}
关于javascript - 映射 JS 对象并将参数合并到子对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60937953/