Javascript merge object with nested properties

function mergeProperties(propertyKey, firstObject, secondObject) {
    var propertyValue = firstObject[propertyKey];

    if (typeof(propertyValue) === "object") {
        return mergeNestedObjects(firstObject[propertyKey], secondObject[propertyKey]);
    } else if (secondObject[propertyKey] === undefined) {
        return firstObject[propertyKey];
    }

    return secondObject[propertyKey];
}

function mergeNestedObjects(firstObject, secondObject) {
    var finalObject = {};

    // Merge first object and its properties.
    for (var propertyKey in firstObject) {
        finalObject[propertyKey] = mergeProperties(propertyKey, firstObject, secondObject);
    }

    // Merge second object and its properties.
    for (var propertyKey in secondObject) {
        finalObject[propertyKey] = mergeProperties(propertyKey, secondObject, firstObject);
    }

    return finalObject;
} 

Pretty old question, but can be useful. A little bit of recursion.

function mergeObjects(og, so) {
    for (var key in so) {
        if (typeof (og[key]) === 'object') {
            mergeObjects(og[key], so[key]);
        } else {
            if (og[key] || typeof (og[key]) === 'boolean') {
                og[key] = so[key];
            }
        }
    }
    return og;
}

mergeObjects(ref, user);