You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套数组转换为普通数组以适配数据库插入需求?

Solution to Transform Your Array Format

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 of Object.keys(meta): Directly access the values of the meta object instead of looping through keys and referencing meta[index]—this makes the code cleaner and more readable.
  • flatMap instead of map: flatMap first maps each item to an array (like map), 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 } = item to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:42:36