Search code examples
javascriptobjecttruncate

Return all properties in JS object to "empty" state


I wonder if there's a utility function in any framework like jQuery to truncate a JS object (there is more than one possible result, not sure what is the most useful yet):

{ // original object
    foo: "bar",
    arr: [1, 2, 3],
    sub: {a: 4, b: 5, subsub: {c: 6}} }

{ // truncated, variant 1
    foo: "",
    arr: [],
    sub: {} }

{ // truncated, variant 2
    foo: "",
    arr: [],
    sub: {subsub: {}} }

{ // truncated, variant 3
    foo: "",
    arr: [],
    sub: {a: 0, b: 0, subsub: {c: 0}} }

If no, is there a solution more clever than to recursively iterate over all properties, check types and remove / reset if necessary?


Solution

  • Call the constructor for each property to create an empty object of the same type.

    for (var k in obj) {
        obj[k] = obj[k] && obj[k].constructor();
    }
    

    This will also return numbers to 0, booleans to false, dates to now, and regexps to empty (but NaNs remain NaN).

    To do this recursively, retaining object-valued properties but emptying them out too (variant 3):

    function truncate(obj) {
        for (var k in obj) {
            var ctor = obj[k] && obj[k].constructor;
            if      (ctor === Object) truncate(obj[k]);
            else if (ctor)            obj[k] = ctor();
        }
    }
    

    To eliminate numbers (variant 2), add a check:

    function truncate(obj) {
        for (var k in obj) {
            var ctor = obj[k] && obj[k].constructor;
            if      (ctor === Object) truncate(obj[k]);
            else if (ctor === Number) delete obj[k];
            else if (ctor)            obj[k] = ctor();
        }
    }