javascript - Javascript递归函数改变对象结构
问题描述
我想将对象结构转换为 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
]
}
]
我想达到以下结构的输出:
{
any: [E,
{
all: [{
all: [A, B],
any: [C, D]
}],
}
]
}
我很确定我需要一个递归函数。我已经尝试过以下方法。这里的问题是输出被覆盖,而我希望在递归函数到达数组的更深层次时扩展它。
recursive(input, output) {
input.forEach((el) => {
if (typeof el !== "number") {
output[el.operator] = el.conditions
this.recursive(el.conditions, output);
}
});
}
提前致谢!
解决方案
这是一个非常简单的函数,旨在转换您输入的一个元素。正如评论中提到的,我不明白输入中的外部数组是做什么用的,为什么输出中没有对应的。但是如果你需要,你可以map
在输入上使用这个函数。(如果它们应该折叠成一个对象,我认为您需要解释您希望如何完成。)
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}
它也不会更改您的输出似乎想要的条件顺序。(因为E
首先。)如果您确实想重新排序它们,有什么要求?
推荐阅读
- laravel - npm 发现 1high 严重性漏洞
- c++ - memory_resource 中放置 new 运算符和 pmr 的区别?
- algorithm - PageRank算法给出奇怪的值
- python - Python:如何将具有分层函数的 ODE 系统拟合到多个数据中
- html - Boostrap 4:如何内联应该隐藏在小屏幕上的文本?
- google-analytics - 获取一系列非连续日期的 Google Analytics(分析)报告?
- oracle - 将pdf文件批量导入oracle表
- python - Python3 Scapy - 嗅探分段的 IP 数据包
- c# - InvalidRequest 在驱动器之间移动 DriveItem
- javascript - 编写异步测试时未触发使用材料 ui 自动完成