moleculeone
moleculeone

Reputation: 221

Removing data from JavaScript objects

I have a JavaScript object info and when I do _(info).values() in the firebug console, I get.

[Object {}, Object { a=6, b=7, more...}, Object { a=2, b=21, more...}, Object {}, Object { a=2, b=9, more...}]

So how can I remove items with Object {} from the above info object by using underscore filter or any other efficient techniques?

Upvotes: 0

Views: 66

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92284

Underscore

_.pick(info, _.filter(_.keys(info), function(key) {
    return _.keys(info[key]).length > 0;
}));

Abstracted into a function

_.filterObject = function(obj, callback) {
    return _.pick(obj, _.filter(_.keys(obj), callback))
};

_.filterObject(info, function(key) {
    return _keys(info[key]).length > 0;
})

http://jsfiddle.net/mendesjuan/2kf8C/1/

Explanation

  • _.pick returns a new object with only the passed in properties

  • _.filter returns just the properties we want, the ones that have keys

Note that this returns a new object, it doesn't modify the original

Upvotes: 0

juvian
juvian

Reputation: 16068

Javascript solution:

var ob={a:{}, b:{ a:6}, c: { a:2}};
function removeEmpty(ob){
    for(var i in ob){
        if(typeof(ob[i])=='object'){
            var keys=Object.keys(ob[i]);
            if(keys.length==0) delete ob[i];
        }
    }
}
removeEmpty(ob);
console.log(ob); // b:{a:6}, c{a:2}

Upvotes: 1

Related Questions