[toc]

对象处理

形如 'a.b.c' 的方式获取对象值

 const getObjectValue = (data,path) => {
    try {
        return path.split('.').reduce((result, current) => result[current], data)
    } catch {
        return undefined
    }
}

判断值为对象类型

function isObject(value) {
    return Object.prototype.toString.call(value) === '[object Object]';
}

判断对象相等

function equalObject (obj1, obj2) {
    if(!isObject(obj1) || !isObject(obj1)) {
        return
    }

    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)

    if(keys1.length != keys2.length) {
        return false
    }

    for(const key in obj1) {
        if(obj1[key] !== obj2[key]) {
            return false
        }
    }

    return true
}

简单的深拷贝,包含数组和对象的值

const deepCopy = (beCopied) => {
    /* 拷贝数组 */ 
    if(beCopied instanceof Array) {
        const arr = []
        for (let i = 0; i < beCopied.length; i++) {
            if(typeof beCopied[i] === 'object') {
                arr[i] = deepCopy(beCopied[i])
            } 
            arr[i] = beCopied[i]
        }
        return arr
    } else if (typeof beCopied === 'object') {
        /* 拷贝对象 */ 
        const obj = {}
        for (let key in beCopied) {
            if(typeof beCopied[key] === 'object') {
                obj[key] = deepCopy(beCopied[key])
            } else {
                obj[key] = beCopied[key]
            }
        }
        return obj
    } else {
        return beCopied
    }
}
Last Updated:
Contributors: Warren