[英]Javascript recursive function to change object structure
我想将 object 结构转换为 Json-rules-engine 可以使用的结构。
我将此数组作为输入,其中 A、B、C、D 和 E 是一些任意条件。
输入
[
{
operator: 'any',
conditions: [
{
operator: 'all',
conditions: [
{ operator: 'all', conditions: [ A, B ] },
{ operator: 'any', conditions: [ C, D ] }
]
},
E
]
}
]
我想达到以下结构的 output :
{
any: [E,
{
all: [{
all: [A, B],
any: [C, D]
}],
}
]
}
我很确定为此我需要一个递归 function 。 我已经尝试过以下方法。 这里的问题是 output 被覆盖,而我希望在递归 function 到达数组的更深层次时扩展它。
recursive(input, output) {
input.forEach((el) => {
if (typeof el !== "number") {
output[el.operator] = el.conditions
this.recursive(el.conditions, output);
}
});
}
提前致谢!
这是一个非常简单的 function,旨在转换您输入的一个元素。 正如评论中提到的,我不明白输入中的外部数组是做什么用的,为什么output中没有对应的。 但是如果你需要的话,你可以只map
这个 function 以上的输入。 (如果它们应该折叠成单个 object,我认为您需要解释您希望如何完成。)
const transform = (x) => Object (x) === x && 'operator' in x? {[x.operator]: (x.conditions || []).map (transform)}: x const input = [{operator: 'any', conditions: [{operator: 'all', conditions: [{operator: 'all', conditions: ['A', 'B']}, {operator: 'any', conditions: ['C', 'D']}]}, 'E']}] console.log (transform (input [0]))
.as-console-wrapper {max-height: 100%;important: top: 0}
它也不会更改您的 output 似乎想要的条件顺序。 (因为E
在前。)如果您确实想重新排序它们,有什么要求?
在此处将我的解决方案添加到其他答案的组合中。 这种transform
对输入t
进行了简单的类型分析,并且具有极好的可读性——
function transform (t) { switch (t?.constructor) { case Object: return { [t.operator]: transform(t.conditions) } case Array: return t.map(transform) default: return t } } const input = [{operator: 'any', conditions: [{operator: 'all', conditions: [{operator: 'all', conditions: ['A', 'B']}, {operator: 'any', conditions: ['C', 'D']}]}, 'E']}] console.log(transform(input))
因为input
被包裹在一个数组中, [...]
, output 也被包裹 -
[
{
"any": [
{
"all": [
{
"all": [
"A",
"B"
]
},
{
"any": [
"C",
"D"
]
}
]
},
"E"
]
}
]
如果您想剥离外部数组,您可以解开输入, transform(input[0])
或解开 output, transform(input)[0]
。
我把它分成两种方法,因为我认为它读起来更容易一些,但如果你愿意,你可以将它们组合起来。 请注意, A
, B
等我需要创建一个字符串以使其可运行。
const convertObj = (obj) => {
return {[obj.operator]: convertConditions(obj.conditions)}
}
const convertConditions = (arr) => {
return arr.map(i => {
if(typeof i == "string") {
return i
}else{
return convertObj(i);
}
})
}
现场示例:
var input = [{ operator: 'any', conditions: [{ operator: 'all', conditions: [{ operator: 'all', conditions: ["A", "B"] }, { operator: 'any', conditions: ["C", "D"] } ] }, "E" ] }] const convertObj = (obj) => { return {[obj.operator]: convertConditions(obj.conditions)} } const convertConditions = (arr) => { return arr.map(i => { if(typeof i == "string") { return i }else{ return convertObj(i); } }) } var result = convertObj(input[0]); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.