首页 > 解决方案 > 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);
      }
    });
  }

提前致谢!

标签: javascriptrecursion

解决方案


这是一个非常简单的函数,旨在转换您输入的一个元素。正如评论中提到的,我不明白输入中的外部数组是做什么用的,为什么输出中没有对应的。但是如果你需要,你可以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首先。)如果您确实想重新排序它们,有什么要求?


推荐阅读