javascript - 嵌套数组递归 - NodeJS
问题描述
我有一个包含动态级别子级的嵌套数组,我想基于这个数组生成一个条件树。
数组的一个例子:
[
{
condition: 'conditionA',
children: [
{
condition: 'conditionA_1',
children: [
...
]
},
]
},
{
condition: 'conditionB',
children: [
...
]
}
]
我想生成一个包含以下条件语句的字符串
if (conditionA) {
if (conditionA_1) {
...
}
} else if (conditionB) {
...
}
有谁知道如何正确处理这个问题?
提前致谢。
解决方案
没有缩进:
只需map
将数组中的每个节点if(condition) { ... }
(递归地),然后将生成的块与" else "
:
function makeSource(arr) {
return arr.map(function(node) {
return "if (" + node.condition + ") { " + (node.children? makeSource(node.children): "") + " }";
}).join(" else ");
}
演示:
function makeSource(arr) {
return arr.map(function(node) {
return "if (" + node.condition + ") { " + (node.children? makeSource(node.children): "") + " }";
}).join(" else ");
}
var array = [ { condition: 'conditionA', children: [ { condition: 'conditionA_1'} ] }, { condition: 'conditionB' } ];
var source = makeSource(array);
console.log(source);
带缩进:
为了实现缩进,我们需要一个变量来保存当前块的深度。只需根据depth
变量在结果字符串的每一行之前重复空格字符即可。depth
在每次递归调用时创建:
function makeSource(arr, depth = 0) {
return arr.map(function(node) {
var str = " ".repeat(depth * 2) + "if (" + node.condition + ") {\n";
if(node.children) {
str += makeSource(node.children, depth + 1);
} else {
str += " ".repeat((depth + 1) * 2); // unecessary, it just indents the empty line to where the code should be
}
return str + "\n" + " ".repeat(depth * 2) + "}";
}).join(" else ");
}
* 2
部分表示压痕编号。如果您想缩进 4 个空格,请将它们替换为* 4
.
演示:
function makeSource(arr, depth = 0) {
return arr.map(function(node) {
var str = " ".repeat(depth * 2) + "if (" + node.condition + ") {\n";
if(node.children) {
str += makeSource(node.children, depth + 1);
} else {
str += " ".repeat((depth + 1) * 2);
}
return str + "\n" + " ".repeat(depth * 2) + "}";
}).join(" else ");
}
var array = [ { condition: 'conditionA', children: [ { condition: 'conditionA_1'} ] }, { condition: 'conditionB' } ];
var source = makeSource(array);
console.log(source);
推荐阅读
- php - 这个 MySQL 查询与 Laravel Query Builder 的等价物是什么?
- ballerina - 如何从 Ballerina 的命令行中读取 int?
- docker - 无法从浏览器访问 Docker 应用程序
- telegram - 电报如何检查另一个用户联系人列表中是否存在新加入的用户号码
- asp.net - 在 Web 主机服务器上使用 WCF 服务
- html - 绝对位置,“阴影/虚线框”没有包裹在“div”周围
- java - 该代码两次生成相同的组合。如何改进它?
- java - 调用泛型方法
- r - 融化多个 id.vars 作为从列表中排除的所有列
- javascript - 按下按钮加载结果后滚动到结果