深度合并

4 阅读1分钟
// 深度合并
function isObj(obj){
    return typeof obj === 'object' && obj !== null
}
function deepMerge(...args){
    const merge = (target, source) => { 
        const _target = {...target}
        Object.keys(source).forEach(key =>{
            const _targetValue = _target[key]
            const _sourceValue = source[key]
            if(!isObj(_sourceValue) || Array.isArray(_sourceValue) || (!isObj(_targetValue) && isObj(_sourceValue)) ){
                _target[key] = _sourceValue
            }else if(isObj(_sourceValue) && isObj(_targetValue)){
                _target[key] = merge(_targetValue,_sourceValue)
            }
        })
        return _target
    }

    return args.reduce((cur,pre)=> merge(cur,pre),{})
}

console.log('deepMerge',deepMerge({a:1,b:2,e:{e1:100,e2:{e3:1000}}},{c:3,d:4,e:{e1:101,e2:{e3:1001,e4:1002}}}))