Function objCopyProps

  • Object helper to copy all of the enumerable properties from the source object to the target, the properties are copied via objDeepCopy. Automatic handling of recursive properties was added in v0.4.4

    Type Parameters

    • T

    Parameters

    • target: T

      The target object to populated

    • source: any

      The source object to copy the properties from

    • Optional handler: ObjDeepCopyHandler

      An optional callback that lets you provide / overide the deep cloning (Since 0.4.4)

    Returns any

    The target object

    Example

    let a: any = { a: 1 };
    let b: any = { b: 2, d: new Date(), e: new TestClass("Hello Darkness") };
    a.b = b; // { a: 1, b: { b: 2} }
    b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}

    function copyHandler(details: IObjDeepCopyHandlerDetails) {
    // details.origin === a
    // details.path[] is the path to the current value
    if (details.value && isDate(details.value)) {
    // So for the date path === [ "b", "d" ] which represents
    // details.origin["b"]["d"] === The Date

    // Create a clone the Date object and set as the "newValue"
    details.value = new Date(details.value.getTime());

    // Return true to indicate that we have "handled" the conversion
    // See objDeepCopy example for just reusing the original value (just don't replace details.value)
    return true;
    }

    return false;
    }

    let c: any = objCopyProps({}, a, copyHandler);

    assert.notEqual(a, c, "check a and c are not the same");
    assert.ok(c !== c.b.a, "The root object won't be the same for the target reference as are are copying properties to our target");
    assert.ok(c.b === c.b.a.b, "Check that the 2 'b' references are the same object");
    assert.ok(c.b.a === c.b.a.b.a, "Check that the 2 'a' references are the same object");
    assert.ok(c.b.d === c.b.a.b.d, "Check that the 2 'd' references are the same object");
    assert.ok(isDate(c.b.d), "The copied date is still real 'Date' instance");
    assert.notEqual(c.b.d, a.b.d, "And the copied date is not the same as the original");
    assert.equal(c.b.d.getTime(), a.b.d.getTime(), "But the dates are the same");

    assert.ok(isObject(c.b.d), "The copied date is now an object");