首页 > 解决方案 > 嵌套数组递归 - NodeJS

问题描述

我有一个包含动态级别子级的嵌套数组,我想基于这个数组生成一个条件树。

数组的一个例子:

[
 {
  condition: 'conditionA',
  children: [
    {
      condition: 'conditionA_1',
      children: [
        ...
      ]
    },
  ]
 },
 {
  condition: 'conditionB',
  children: [
    ...
  ]
 }
]

我想生成一个包含以下条件语句的字符串

if (conditionA) {
  if (conditionA_1) {
    ...
  }
} else if (conditionB) {
  ...
}

有谁知道如何正确处理这个问题?

提前致谢。

标签: javascriptarraysnode.jsrecursion

解决方案


没有缩进:

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


推荐阅读