javascript Flat JSON to JSON with children

brccelvz  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(156)

我有一个包含以下结构的JSON:

const content = [
  { title: "Item 1", metaData: { "level": 1, "desc": "Some Desc 1", "displayOnOverview": true }},
  { title: "Item 2", metaData: { "level": 2, "desc": "Some Desc 2", "displayOnOverview": true }},
  { title: "Item 3", metaData: { "level": 2, "desc": "Some Desc 3", "displayOnOverview": false }},
  { title: "Item 4", metaData: { "level": 3, "desc": "Some Desc 4", "displayOnOverview": true }},
  { title: "Item 5", metaData: { "level": 1, "desc": "Some Desc 5", "displayOnOverview": true }}
];

根据上面的内容,我需要构建以下输出:

{
  "title": "Item 1",
  "metaData": {
    "desc": "Some Desc 1",
    "displayOnOverview": true
  },
  "subNav": [
    {
      "title": "Item 2",
      "metaData": {
        "desc": "Some Desc 2",
        "displayOnOverview": true
      }
    },
    {
      "title": "Item 3",
      "metaData": {
        "desc": "Some Desc 3",
        "displayOnOverview": false
      },
      "subNav": [
        {
          "title": "Item 4",
          "metaData": {
            "desc": "Some Desc 4",
            "displayOnOverview": true
          }
        }
      ]
    }
  ]
},
{
  "title": "Item 6",
  "metaData": {
    "desc": "Some Desc 6",
    "displayOnOverview": true
  }
}

我写了一些代码(如下所示),它可以工作,但只是在顶层,只要它找到"title": "Item 3"它就停止工作,很肯定我错过了一些东西:

// Create root for top-level node(s)
    const root = [];

    sideNavData.forEach((node, index) => {
        const nodeLevel = node.metaData.level;

        if (root.length === 0) {
            return root.push(node)
        }

        const previousLevel = root[index - 1].metaData.level;

        if (previousLevel === nodeLevel) {
            return root.push(node)
        } else {
            return root[index - 1]['subNav'] = node
        }
    });

    console.log(root);

我能得到一些关于如何实现这一目标的想法吗?

jvlzgdj9

jvlzgdj91#

您在这里:

const content = [
  { title: "Item 1", metaData: { "level": 1 }},
  { title: "Item 2", metaData: { "level": 2 }},
  { title: "Item 3", metaData: { "level": 2 }},
  { title: "Item 4", metaData: { "level": 3 }},
  { title: "Item 5", metaData: { "level": 1 }}
];

function buildNestedStructure(data) {
  const topLevelItems = [];
  const itemMap = {};

  for (const item of data) {
    const { title, metaData } = item;
    const newItem = { title, metaData };

    if (metaData.level === 1) {
      topLevelItems.push(newItem);
    } else {
      const parentLevel = metaData.level - 1;
      const parentItem = itemMap[parentLevel];

      if (!parentItem.subNav) {
        parentItem.subNav = [];
      }

      parentItem.subNav.push(newItem);
    }

    itemMap[metaData.level] = newItem;
  }

  return topLevelItems;
}

const output = buildNestedStructure(content);
console.log(JSON.stringify(output, null, 2));

相关问题