欢迎阅读『Tag标签列表』

递归 判断条件 赋值

 // 递归 判断条件 赋值
        var data = [
            {
                "addr": "00001",
                "parent": "00002",
                "num": "00002",
            },
            {
                "addr": "00002",
                "parent": "00002",
                "num": "00002",
            },
            {
                "addr": "00002",
                "parent": "00002",
                "num": "00002",
            },
            {
                "addr": "00003",
                "parent": "00003",
                "num": "00002",
            },
            {
                "addr": "00004",
                "parent": "00003",
                "num": "00002",
            },
            {
                "addr": "00003",
                "parent": "00002",
                "num": "00002",
            }
        ];

        function deepClone(obj) {
            let objClone = Array.isArray(obj) ? [] : {};
            if (obj && typeof obj === "object") {
                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        //判断ojb子元素是否为对象,如果是,递归复制
                        if (obj[key] && typeof obj[key] === "object") {
                            objClone[key] = deepClone(obj[key]);
                        } else {
                            //如果不是,简单复制
                            objClone[key] = obj[key];
                        }
                    }
                }
            }
            return objClone;
        };
        var data2 = deepClone(data);
        console.log(data2);
        for (var i = 0; i < data.length; i++) {
            if (data[i].addr == data[i].parent && data[i].addr == data[i].num) {
                data[i].childer = data2[i];
            }
        }
        console.log(data);

posted @ 2021-05-25 21:21  兔子零-A酱  阅读(136)  评论(0编辑  收藏  举报