Created
October 16, 2015 07:38
-
-
Save Icehunter/2bb5037596d762767893 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// linting rules prevent modifying Object directly | |
var extend = Object; | |
extend.compact = function (obj) { | |
var self = this; | |
function compactArray(array) { | |
return array.filter(function (value) { | |
return value; | |
}); | |
} | |
if (Array.isArray(obj)) { | |
obj = compactArray(obj); | |
} | |
for (var key in obj) { | |
if (typeof obj[key] == 'object') { | |
if (Array.isArray(obj[key])) { | |
obj[key] = compactArray(obj[key]); | |
} | |
self.compact(obj[key]); | |
} | |
if (!obj[key]) { | |
delete obj[key]; | |
} | |
} | |
if (obj) { | |
return obj; | |
} | |
} | |
// tests | |
var obj = { | |
true: { | |
string: 'string', | |
number: 1, | |
boolean: true, | |
object: {}, | |
array: [{ | |
false: { | |
string: '1', | |
number: 0, | |
boolean: false, | |
null: null | |
} | |
}, 1, 0, true] | |
}, | |
false: { | |
string: '', | |
number: 0, | |
boolean: false, | |
null: null | |
}, | |
one: 0 | |
}; | |
var array = [1, 2, 3, 0, { | |
string: '', | |
number: 0, | |
boolean: false, | |
null: null | |
}]; | |
Object.compact(obj); | |
Object.compact(array); | |
console.log(obj); | |
console.log(array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment