我有一个嵌套数组包含动态数量级别的子项,我想基于此数组生成条件树。
数组的一个例子:
[
{
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);
const input = [
{
condition: 'conditionA',
children: [
{
condition: 'conditionA_1',
children: [
]
},
]
},
{
condition: 'conditionB',
children: [
]
}
]
const createSource = arr =>{
let source = "";
if(arr.length === 0){
return source;
}
arr.forEach((value,index) =>{
source+="if( "+value.condition+" ){";
if(value.children){
source+=createSource(value.children)
}
source+="}" + (index+1 < arr.length ? " else " : "");
})
return source;
}
console.log(createSource(input))