我需要创建一个方法来转换具有以下结构的动态JSON
export interface Regole {
descrizioneRegola: string;
naturaGiuridica: string;
regolaPerCollegamento: RegolaPerCollegamento[];
or?: OperatoreLogico;
and?: OperatoreLogico;
not?: OperatoreLogico;
}
export interface OperatoreLogico {
regolaPerCollegamento?: RegolaPerCollegamento[];
or?: OperatoreLogico;
and?: OperatoreLogico;
not?: OperatoreLogico;
}
export interface RegolaPerCollegamento {
tipoCollegamentoEsistente?: number;
tipoCollegamento?: number;
quantita?: string;
minimo?: number;
massimo?: number;
esattamente?: number;
}
其中键**“或”,“和”,“不是”**可以是动态的。
例如,我可以在输入中输入这个Json
let json: OperatoreLogico = {
"or": {
"and": {
"regolaPerCollegamento": [
{
"tipoCollegamentoEsistente": 115,
"quantita": "NESSUNO"
},
{
"tipoCollegamentoEsistente": 118,
"quantita": "NESSUNO"
}
]
},
"or": {
"regolaPerCollegamento": [
{
"tipoCollegamento": 115,
"minimo": 1
},
{
"tipoCollegamento": 118,
"minimo": 1
}
]
}
}
}
并转换为以下输出:
({tipoCollegamentoEsistente: 115, quantita: "NESSUNO"} && {tipoCollegamentoEsistente: 118, quantita: "NESSUNO"}) || ({tipoCollegamento: 115, minimo: 1} || {tipoCollegamento: 115, minimo: 1})
正如你所看到的,在上面的例子中,“和”运算符需要对数组中的两个对象执行“和”“,内部的**”或"“是数组中的两个对象,外部的”或“"是连接内部的”和"和“或”**“的结果。
我尝试创建一个递归方法,但似乎不起作用
export function convertToRule(operatoreLogico: OperatoreLogico, initial?: OperatoreLogico, operator?: string, result?: string): string {
const initialJson = { ...operatoreLogico };
if (operatoreLogico.regolaPerCollegamento) {
const regole = Array.isArray(operatoreLogico.regolaPerCollegamento)
? operatoreLogico.regolaPerCollegamento
: [operatoreLogico.regolaPerCollegamento];
const regoleString = regole.map((regola: any) => {
const properties = Object.keys(regola).map((key) => {
return `"${key}": ${JSON.stringify(regola[key])}`;
}).join(', ');
return `{ ${properties} }`;
}).join(operator);
let op = Object.keys(initial!)[0];
if (op === 'and') {
delete initial?.and;
result = '(' + result + ' && ' + regoleString+ ')';
convertToRule(initial!, undefined, undefined, result + regoleString);
} else {
delete initial?.or;
result = '(' + result + ' || ' + regoleString + ')';
convertToRule(initial!, undefined, undefined, result + regoleString);
}
return `( ${regoleString} )`;
} else if (operatoreLogico.and) {
const andRules = Array.isArray(operatoreLogico.and) ? operatoreLogico.and : [operatoreLogico.and];
andRules.map((andRule) => {
return convertToRule(andRule, initialJson, ' && ', result);
})
return '';
} else if (operatoreLogico.or) {
const orRules = Array.isArray(operatoreLogico.or) ? operatoreLogico.or : [operatoreLogico.or];
orRules.map((orRule) => {
return convertToRule(orRule, initialJson, ' || ', result);
})
return '';
} else {
return '';
}
}
1条答案
按热度按时间pdsfdshx1#
这应该是你想要的:
也就是说,这是一种奇怪的表示AST的方式,你可能会更好地使用这样的结构: