项目场景:
在做项目的时候,需要将tree结构数据拼接成类似sql语句的字符串
问题描述
const obj = {
rel: 'and',
children: [
{
rel: 'and',
children: [
{
rel: 'and',
children: [
{
rel: 'or',
children: [
{ value: 1, children: [] },
{ value: 2, children: [] },
],
},
{
rel: 'and',
children: [
{ value: 3, children: [] },
{ value: 4, children: [] },
],
},
],
},
{ value: 5, children: [] },
],
},
{
rel: 'or',
children: [
{ value: 6, children: [] },
{ value: 7, children: [] },
],
},
{
value: 8,
children: [],
},
],
};
需要将上面的数据转为字符串输出为:
'(((1 or 2) and (3 and 4) ) and 5) and (6 or 7) and 8'
解决方案:
提示:利用递归
代码如下:
function walk(obj) {
let ret = ""
let list = [];
if (obj.children === undefined || !Array.isArray(obj.children) || obj.children.length === 0) {
return obj.value;
}
for (let i = 0; i < obj.children.length; i++) {
let item = obj.children[i];
let out = walk(item);
if (out !== undefined) list.push(out);
}
for (let i = 0; i < list.length; i++) {
if (ret !== "") ret += " " + obj.rel + " ";
if ((list[i]+"").indexOf("or") >= 0 || (list[i] + "").indexOf("and") >= 0) ret += "(" + list[i] + ") ";
else ret += list[i];
}
return ret.replaceAll(" ", " ");
}
本文介绍了一个JavaScript实现,通过递归方法将树形数据结构转换为类似SQL的字符串表达式。给定的数据示例展示了如何将嵌套的逻辑运算符(如AND和OR)及值节点转化为相应的字符串,如'(((1or2)and(3and4))and5)and(6or7)and8'。这个方法对于处理复杂逻辑表达式的数据转换非常有用。
2600

被折叠的 条评论
为什么被折叠?



