index.js 1.97 KB
Newer Older
liuxin committed
1 2
export default class Utils {
    static toDepthObject(obj) {
fukai committed
3
        var target = {};
liuxin committed
4
        for (var key in obj) {
fukai committed
5 6
            var keyArr = key.split("_"); //以下划线或分割
            var tempobj = target;
liuxin committed
7 8
            for (var i = 0; i < keyArr.length - 1; i++) {
                if (tempobj[keyArr[i]])
fukai committed
9
                    tempobj = tempobj[keyArr[i]];
liuxin committed
10
                else {
fukai committed
11 12
                    tempobj[keyArr[i]] = {};
                    tempobj = tempobj[keyArr[i]];
liuxin committed
13
                }
fukai committed
14 15
            }
            //给叶子元素赋值
liuxin committed
16
            tempobj[keyArr[keyArr.length - 1]] = obj[key];
fukai committed
17 18 19
        }
        return target;
    }
liuxin committed
20 21 22 23 24
    static flatObject(obj, target, pkey) {
        target = target || {};
        for (var key in obj) {
            var nkey = pkey ? pkey + "_" + key : key;
            if (!obj[key])
25
                target[nkey] = obj[key];
liuxin committed
26
            else if (obj[key] instanceof Array)
27
                target[nkey] = obj[key];
liuxin committed
28 29 30 31 32 33 34 35
            else if (obj[key] instanceof Date)
                target[nkey] = obj[key];
            else if (typeof obj[key] == "object")
                Utils.flatObject(obj[key], target, nkey); //递归赋值
            else
                target[nkey] = obj[key];
        }
        return target;
fukai committed
36
    }
liuxin committed
37
    static copyValueFromVO(model, vo) {
fukai committed
38
        var target = model;
liuxin committed
39
        for (var key in vo) {
fukai committed
40 41
            var keyArr = key.split("_"); //以下划线或分割
            var tempobj = target;
liuxin committed
42 43
            for (var i = 0; i < keyArr.length - 1; i++) {
                if (tempobj[keyArr[i]])
fukai committed
44
                    tempobj = tempobj[keyArr[i]];
liuxin committed
45
                else {
fukai committed
46 47
                    tempobj = null;
                    break;
liuxin committed
48
                }
fukai committed
49 50
            }
            //给叶子元素赋值
liuxin committed
51
            if (tempobj) {
fukai committed
52
                let leafProp = keyArr[keyArr.length - 1];
liuxin committed
53 54
                if (tempobj.hasOwnProperty(leafProp))
                    tempobj[leafProp] = vo[key];
fukai committed
55 56 57 58 59
            }
        }
        return target;
    }
}