解解对象结构

dessolve Object structure

本文关键字:结构 对象      更新时间:2023-09-26

我从我的 REST-API 中获取一个对象,如下所示

var obj = {
            array1: [
                {
                    "elm": 1, children: [
                    {
                        "elm": 2, children: [
                        {
                            "elm": 3, children: [
                            {
                                "elm": 4, children: [
                                {"elm": 5}
                            ]
                            }
                        ]
                        }
                    ]
                    }
                ]
                }
            ],
            array2: [
                {
                    "elm": 6, children: [
                    {
                        "elm": 7, children: [
                        {
                            "elm": 8, children: [
                            {
                                "elm": 9, children: [
                                {"elm": 10}
                            ]
                            }
                        ]
                        }
                    ]
                    }
                ]
                }
            ]
        };

由于更改了接口并且无法访问 api 及其结构构建,我必须将对象解为如下所示的内容:

    var newObj = {
        array1: [
            {
                "elm": 1, children: [
                {"elm": 2},
                {"elm": 3},
                {"elm": 4},
                {"elm": 5}
            ]
            }
        ],
        array2: [
            {
                "elm": 6, children: [
                {"elm": 7},
                {"elm": 8},
                {"elm": 9},
                {"elm": 10}
            ]
            }
        ]
    };

有没有更简单的方法可以解散物体,而不会循环穿过每个孩子?

也许这对你有用...

var obj = { array1: [{ "elm": 1, children: [{ "elm": 2, children: [{ "elm": 3, children: [{ "elm": 4, children: [{ "elm": 5 }] }] }] }] }], array2: [{ "elm": 6, children: [{ "elm": 7, children: [{ "elm": 8, children: [{ "elm": 9, children: [{ "elm": 10 }] }] }] }] }] },
    result = function (object) {
        function dig(a) {
            this.push({ elm: a.elm });
            Array.isArray(a.children) && a.children.forEach(dig, this);
        }
        var r = {};
        Object.keys(object).forEach(function (k) {
            object[k].forEach(function (a) {
                var array = [];
                r[k] = r[k] || [];
                r[k].push({ elm: a.elm, children: array });
                Array.isArray(a.children) && a.children.forEach(dig, array);
            });
        });
        return r;
    }(obj);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');