项目场景:
在做项目的时候,需要将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(" ", " ");
}