js複雜對象和簡單對象的簡單轉化

var course = {
    teacher :{
        teacherId:001,
        teacherName:"王"
    },
    course : {
        courseId : 120,
        courseName : "開心一笑"
    },
    admin : "班主任"
}
var obj_help = {
    obj_tansform: function (data, temple) {
        //子對象轉化爲指定結構的複雜對象
        var _self = this;
        var callee = function (obj) {
            for (key in obj) {
                if (typeof obj[key] === "object" && (!_self.obj_isArray(obj[key]))) {
                    obj[key] = callee(obj[key]);
                } else {
                    obj[key] = data[key] ? data[key] : "";
                }
            }
            return obj;
        }
        return callee(temple);
    },
    obj_revange: function (data) {
        //轉化爲簡單對象(不存在子對象)
        var _self = this;
        var _data = {};
        var Rcallee = function (obj) {
            for (key in obj) {
                if (typeof obj[key] === "object" && (!_self.obj_isArray(obj[key]))) {
                    obj[key] = Rcallee(obj[key]);
                } else {
                    _data[key] = obj[key];
                }
            }
        }
        Rcallee(data);
        return _data;
    },
    obj_isArray: function (arr) {
        return arr != null && typeof arr === "object" && 'splice' in arr && "join" in arr;
    },
    removeBlank: function (str) {
        try {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        } catch (e) {
            console.log(str);
        }
    }
}
console.log(obj_help.obj_revange(course));
View Code

輸出結果json

假若這樣調用ide

var teacherMes = {
    teacherName:"",
    course:{
        teacherId :"",
        courseMes :{
            courseId:"",
            courseName:"",
            admin:""
        }
    }
}
var data = obj_help.obj_revange(course);

console.log(obj_help.obj_tansform(data,teacherMes));
View Code

那麼輸出結果函數

第一個函數是按照你給的模版初始化對象,第二個是把複雜的對象的子對象的屬性所有提取到同一個對象下,this

實際的能夠使用的地方並很多,好比後臺返回的json是一個複雜的對象,那麼你能夠直接簡單化處理,一樣提交數據時使用按照模版格式化數據後提交。spa

能夠大大的減小因爲屬性在子對象下形成的困擾。3d

相關文章
相關標籤/搜索