如何将深层嵌套对象文字转换为对象数组?

时间:2018-12-12 10:55:42

标签: javascript ecmascript-6

我正在尝试使用ant design UI framework构建treeselect组件,该组件的要求是以特定格式(对象数组)提供treeData,但是在我的应用程序中,我将数据作为对象获取文字,如下所示。

output = {"Node3":{
    "Node": "Node3",
    "children": {
        "Node3A" : {
            "Node": "Node3A",
            "children": {
                "Node3A1": {
                    "Node": "Node3A1",
                    "children": {
                        "Node3A1": {
                            "Node": "Node3A1x"
                        },
                        "Node3A1":{
                            "Node": "Node3A1y"
                        },
                        "Node3A1": {
                            "Node": "Node3A1z"
                        }
                    }
                },
                "Node3A2":{
                    "Node": "Node3A2"
                },
                "Node3A3":{
                    "Node": "Node3A3"
                }
            }
        }
    }}}

我想将其转换为如下所示的输出,以便我可以将此数据作为treeData提供,以在树选择组件中获得所需的输出。

{
    "Node": "Node3",
    "children": [
        {
            "Node": "Node3A",
            "children": [
                {
                    "Node": "Node3A1",
                    "children":
                        [
                            {
                                "Node": "Node3A1x"
                            },
                            {
                                "Node": "Node3A1y"
                            },
                            {
                                "Node": "Node3A1z"
                            }
                        ]
                },
                {
                    "Node": "Node3A2"
                },
                {
                    "Node": "Node3A3"
                }
            ]
        }

基本上,我希望以某种方式获得输出,以将对象文字的子代属性转换为对象数组。寻找Javascript解决方案(最好是ES6)

1 个答案:

答案 0 :(得分:0)

const input = {
  "Node3": {
    "Node": "Node3",
    "children": {
      "Node3A": {
        "Node": "Node3A",
        "children": {
          "Node3A1": {
            "Node": "Node3A1",
            "children": {
              "Node3A1x": {
                "Node": "Node3A1x"
              },
              "Node3A1y": {
                "Node": "Node3A1y"
              },
              "Node3A1z": {
                "Node": "Node3A1z"
              }
            }
          },
          "Node3A2": {
            "Node": "Node3A2"
          },
          "Node3A3": {
            "Node": "Node3A3"
          }
        }
      }
    }
  }
};

function transform(obj) {
  if (obj.children) {
    obj.children = Object.values(obj.children).map(transform);
  }
  return obj;
}

const result = transform(Object.values(input).pop());
console.log(result);