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;
}
So:
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:will filter out items in
listthat have a “falsey” value in thefooproperty.Edit:
On further thought,
undefinedseems to be considered “empty” by both jQuery and Prototype. jQuery’sextendfunction can do what I think you’re aiming for withundefined, albeit with a slightly different syntax and without mutating the passed argument:Swap
"jQuery"with"Object"for the Prototype equivalent.