js递归函数,返回嵌套的json



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

{
"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: {}
}
}

类似的东西?

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)));

最新更新