【问题标题】:js recursive function that returns a nested json返回嵌套json的js递归函数
【发布时间】:2018-11-11 06:42:24
【问题描述】:

我正在尝试创建一个递归函数,该函数将生成嵌套的项目结构。 此文件中的每个项目都有一个指向其子项的指针和一个停止值,如您在此处看到的:

{
    "1": {
        "id": 1,
        "next_1": 2,
        "next_2": 3,
        "stop": false
    },
    "2": {
        "id": 2,
        "next_1": 3,
        "next_2": 4,
        "stop": false
    },
    "3": {
        "id": 3,
        "stop": true
    },
    "4": {
        "id": 4,
        "stop": true
    }
}

这个递归函数应该获得一个起始索引,它将从该索引构建树并返回一个嵌套字典,如下所示:

{
    1: {
        2: {
            3: {},
            4: {}
        },
        3: {}
    }
}

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您的最终目标是什么?这是作业吗?
  • 我的目标是从这个 json 创建一个可视化树,我尝试了很多东西,但我找不到正确的方法@DerekPollard

标签: javascript json recursion


【解决方案1】:

这样的?

const data = {
    "1": {
        "id": 1,
        "next_1": 2,
        "next_2": 3,
        "stop": false
    },
    "2": {
        "id": 2,
        "next_1": 3,
        "next_2": 4,
        "stop": false
    },
    "3": {
        "id": 3,
        "stop": true
    },
    "4": {
        "id": 4,
        "stop": true
    }
};


function build(root, idx) {
  const item = root[idx];
  const result = {};
  if(!item.stop) {
    result[item.next_1] = build(root, item.next_1);
    result[item.next_2] = build(root, item.next_2);
  }
  
  return result;
}

alert(JSON.stringify(build(data, 1)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 2021-01-23
    • 2017-02-16
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多