Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created April 12, 2015 18:23
Show Gist options
  • Save lamchau/c93aa3659707a3594ef0 to your computer and use it in GitHub Desktop.
Save lamchau/c93aa3659707a3594ef0 to your computer and use it in GitHub Desktop.
describe('filterObject', function () {
it('should filter out falsey values', function () {
var actual = filterObject({
empty: '',
depth: 0,
nested: {
empty: '',
depth: 1,
nested: {
empty: '',
str: 'hello',
depth: 2,
value: false,
other: true
}
}
});
var expected = {
nested: {
depth: 1,
nested: {
str: 'hello',
depth: 2,
other: true
}
}
};
expect.expect(actual).to.deep.equal(expected);
});
});
function filterObject(object, predicate) {
if (typeof predicate !== 'function') {
predicate = function(value, key, o) {
if (!value) {
delete o[key];
}
};
}
if (typeof object === 'object') {
for (var key in object) {
predicate.call(this, object[key], key, object);
filterObject(object[key], predicate);
}
}
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment