表达式层级json转可读表达式

44 阅读1分钟

层级递归显示条件表达式

  const list = {
    ops: 'and',
    nodeId: 'a1',
    type: 'start',
    children: [
      {
        key: 'kg',
        op: '>',
        value: 10,
        nodeId: 'b1',
      },
      {
        ops: 'or',
        nodeId: 'b2',
        children: [
          {
            key: 'height',
            op: '<',
            value: 20,
            nodeId: 'c1',
          },
          {
            key: 'weight',
            op: '>',
            value: 30,
            nodeId: 'c2',
          },
        ],
      },
    ],
  }

  function convertToExpression(node) {
    if (node.ops === 'and') {
      const childrenExpressions = node.children.map((child) => { return convertToExpression(child) });
      console.log('childrenExpressions', childrenExpressions);
      return childrenExpressions.join(' and ');
    } else if (node.ops === 'or') {
      const childrenExpressions = node.children.map((child) => { return convertToExpression(child) });
      return `(${childrenExpressions.join(' or ')})`;
    } else {
      return `${node.key} ${node.op} ${node.value}`;
    }
  }

  const content = convertToExpression(list); // kg > 0 and (height < 20 or weight > 10)