Reputation: 12561
We're using jQuery on a less UI-intensive project whereas we have been using ExtJS on other projects. Regardless, I'm curious if any of the prevalent libraries such as ExtJS, jQuery, or others, provide a utility for "pruning" objects? By which I mean, deleting keys if they don't contain values.
I've devised my own (naive) implementation as follows, so its no biggie. Still though just curious as I believe this could be generally useful. I've googled for "jquery prune object" but no results seem worth investigating though of course I could be wrong ;)
function pruneObj(obj) {
var empty = [];
for (var attr in obj) {
if (!obj[attr]) {
empty.push(attr); //rather than trying to delete the element in place
}
}
for (var i=0, n=empty.length; i<n; i++) {
delete(obj[empty[i]]);
}
return obj;
}
Upvotes: 0
Views: 143
Reputation: 117008
So:
var obj = { hasFoo: false, count: 0 }
would (after a call to prunObj(obj)
) be just {}
?
I don't think any library out there would make the assumption of what values to deem "empty". It's too destructive/mutative a function to include as part of a standard set of utility functions.
Many libraries or browsers include a facility to filter out items from arrays that don't meet a certain criteria. Eg filter
:
list.filter(function(item){
return !item.foo
})
will filter out items in list
that have a "falsey" value in the foo
property.
Edit:
On further thought, undefined
seems to be considered "empty" by both jQuery and Prototype. jQuery's extend
function can do what I think you're aiming for with undefined
, albeit with a slightly different syntax and without mutating the passed argument:
A = { hasFoo: false, count: 0, foo: null, bar: undefined };
B = jQuery.extend({}, A); // B = { hasFoo: false, count: 0, foo: null }
Swap "jQuery"
with "Object"
for the Prototype equivalent.
Upvotes: 1