将嵌套对象转换为递归数组或javascript es6中的嵌套数组

时间:2019-05-26 13:40:45

标签: javascript arrays json recursion ecmascript-6

我处理了要转换为递归数组或嵌套数组的嵌套对象。

我尝试迭代对象,如下所示,但是它正在创建数组的单个对象。

任何人都可以提出建议或分享您的想法对我有帮助

        iterate(obj) {
                for (let property in obj) {
                  this.configArray.push({key: property,children: [], isValue: false, value: ''});
                    if (obj.hasOwnProperty(property)) {
                      const index = Object.keys(obj).indexOf(property);
                        if (typeof obj[property] == "object") {
                            this.iterate(obj[property]);
                        }
                        else {
                            this.configArray[index].children.push({ key: property, value: obj[property], isValue: true, children: [] });
                        }
                    }
                }
            }

输入

{
"Parent 1": {
    "11": "Child 1",
    "12": "Child 2",
},
"Parent 2": {
    "20": {
        "21": "Grand Child 1",
        "22": "Grand Child 2",          
    }
},
"Parent 3": {
    "31": "Child 1",
    "32": "Child 2",
}

}

输出

  [
{
    key: "Parent 1",
    value: "",
    children: [
        { key: 11, value: "Child 1", children: [] },
        { key: 12, value: "Child 2", children: [] }
    ]
},
{
    key: "Parent 2",
    value: "",
    children: [
        {
            key: 20,
            value: "",
            children: [
                { key: 21, value: "Grand Child 1", children: [] },
                { key: 22, value: "Grand Child 2", children: [] }
            ]
        }
    ]
},
{
    key: "Parent 3",
    value: "",
    children: [
        { key: 31, value: "Child 1", children: [] },
        { key: 32, value: "Child 2", children: [] }
    ]
},
];

1 个答案:

答案 0 :(得分:1)

如果value是对象,则可以采用递归方法并映射值或子项。

function transform(object) {
    return Object
        .entries(object)
        .map(([key, value]) => Object.assign({ key }, value && typeof value === 'object'
            ? { value: '', children: transform(value) }
            : { value, children: [] }
        ));
}

var data = { "Parent 1": { 11: "Child 1", 12: "Child 2" }, "Parent 2": { 20: { 21: "Grand Child 1", 22: "Grand Child 2" } }, "Parent 3": { 31: "Child 1", 32: "Child 2" } },
    result = transform(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }