SOURCE

function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
}

function assign(obj1, obj2) {
    const l1 = Object.keys(obj1).length
    const l2 = Object.keys(obj2).length
    if (l2 > l1) {
        return assign(obj2, obj1)
    }
    const res = {}
    for (const key of Object.keys(obj1)) {
        if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
            const arr = mergeArr(obj1[key], obj2[key])
            res[key] = arr
        } else if (isPlainObject(obj1[key]) && isPlainObject(obj2[key])) {
            res[key] = assign(obj1[key], obj2[key])
        } else if (typeof obj1[key] === typeof obj2[key]) {
            res[key] = obj2[key]
        } else if (typeof obj2[key] === 'undefined') {
            res[key] = obj1[key]
        } else {
            throw new Error('error')
        }
    }
    for (const key of Object.keys(obj2)) {
        if (!res[key]) {
            res[key] = obj2[key]
        }
    }
    return res
}

function mergeArr(arr1, arr2) {
    const oldArr = [...arr1, ...arr2]
    const newArr = []
    let o = {}
    oldArr.forEach(item => {
        if (typeof item === 'object') {
            o = assign(o, item)
            return
        }
        newArr.push(item)
    })
    if (Object.keys(o).length !== 0)
        newArr.push(o)
    return newArr
}
const obj1 = {
    a: [1],
};

const obj2 = {
    a: "a",
};
console.log(assign(obj1, obj2))
console 命令行工具 X clear

                    
>
console