如何将嵌套数组转换为普通数组以适配数据库插入需求?
Looking at your code, the main issue is that your current implementation returns a nested array (an array of arrays) instead of the flat array of objects you need for your database. Let's fix that.
What Was Wrong?
Your buildTvTimeline function uses map on Object.keys(meta), and each iteration returns data—which is an array created by dates.map(...). This means the result is an array where each element is another array of objects. Your subsequent Object.keys(timeline).map(...) doesn't resolve this; it just preserves the nested structure.
Corrected Code
Here's the revised function that produces a flat array of your desired format:
const buildTvTimeline = (r: Data) => { const meta = get(r, ["meta", "tv"], []); // Use flatMap to automatically flatten nested arrays into a single list return Object.values(meta).flatMap((item) => { const { game, tile, dates } = item; // Attach game/tile to each date entry, then flatMap combines all results return dates.map((date) => ({ ...date, tile: tile, game: game })); }); }; // Usage const timeline = buildTvTimeline(r); set(r, ["timeline", "tv"], timeline);
Key Improvements:
Object.values(meta)instead ofObject.keys(meta): Directly access the values of themetaobject instead of looping through keys and referencingmeta[index]—this makes the code cleaner and more readable.flatMapinstead ofmap:flatMapfirst maps each item to an array (likemap), then flattens the result by one level. This turns our array of arrays into a single flat array of objects, which is exactly what you need for database insertion.- Destructuring: Used
const { game, tile, dates } = itemto simplify variable access and make the code more concise.
Example Output
If your original meta object looks like this:
{ "0": { game: "Game1", tile: "Tile1", dates: [{ date: "2024-01-01" }, { date: "2024-01-02" }] }, "1": { game: "Game2", tile: "Tile2", dates: [{ date: "2024-01-03" }] } }
The corrected function will return:
[ { date: "2024-01-01", tile: "Tile1", game: "Game1" }, { date: "2024-01-02", tile: "Tile1", game: "Game1" }, { date: "2024-01-03", tile: "Tile2", game: "Game2" } ]
Which matches your target flat array format perfectly.
内容的提问来源于stack exchange,提问作者AdamSulc

