CodeManX
CodeManX

Reputation: 11905

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?

Upvotes: 2

Views: 208

Answers (3)

user663031
user663031

Reputation:

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();
    }
}

Upvotes: 7

Nick Manning
Nick Manning

Reputation: 2989

Object.prototype.clear=function(){
    for (prop in this){
        if (typeof this[prop]==='string') this[prop]='';
        else if (this[prop] instanceof Array) this[prop]=[];
        else{
            this[prop]={}//variant 1
        }
    }
    return this;
}

.

var obj={
    foo:"bar", 
    arr:[1,2,3],
    sub:{b:4,c:5,subsub:{e:6}}
}

obj.clear()//returns {foo:"",arr:[],sub:{}}

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You may be looking for OMIT, part of underscore.js.

omit_.omit(object, *keys) Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid'); => {name: 'moe', age: 50} _.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) { return _.isNumber(value); }); => {name: 'moe', userid: 'moe1'}

Upvotes: 1

Related Questions