💾mergeWithoutOverride()

// like Object.assign() but different
function mergeWithoutOverride(target, ...sources) {

    for (let source of sources) {
        // doesn't handle Symbol properties
        for (let key of Object.keys(source)) { 
            // doesn't override existing properties
            if (!(key in target)) target[key] = source[key];
        }
    }
    
    return target;
}

💈範例:

Object.assign({x:1}, {x:2, y:2}, {x:3, y:3, z:3})
// { x: 3, y: 3, z: 3 } (⭐️ override with new values)

mergeWithoutOverride({x:1}, {x:2, y:2}, {x:3, y:3, z:3})
// { x: 1, y: 2, z: 3 } (⭐️ keep old values)

Last updated