我有一个嵌套的数组,其中包含动态数量的子级,我想基于此数组生成条件树。
数组的示例:
[
{
condition: 'conditionA',
children: [
{
condition: 'conditionA_1',
children: [
...
]
},
]
},
{
condition: 'conditionB',
children: [
...
]
}
]
我想生成一个包含以下条件语句的字符串
if (conditionA) {
if (conditionA_1) {
...
}
} else if (conditionB) {
...
}
有人对如何正确处理有任何想法吗?
谢谢。
答案 0 :(得分:0)
只需将数组中的每个节点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);
答案 1 :(得分:0)
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))