-
Notifications
You must be signed in to change notification settings - Fork 0
/
null-prune.js
67 lines (58 loc) · 1.38 KB
/
null-prune.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(function (name, definition) {
if (typeof define === 'function') {
// AMD
/* eslint-env amd */
define(definition)
} else if (typeof module !== 'undefined' && module.exports) {
// Node.js
module.exports = definition()
} else {
// Browser
window[name] = definition()
}
})('nullPrune', function () {
function isObject (input) {
return input && (typeof input === 'object')
}
function ownKeys (obj) {
var key
var ownKeys = []
var hasOwnProperty = Object.prototype.hasOwnProperty
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
ownKeys.push(key)
}
}
return ownKeys
}
function nullPrune (inputObject, context) {
var objectKey = context.objectKey
var parentObject = context.parentObject
var keys = ownKeys(inputObject)
var k
var key
var node
for (k in keys) {
key = keys[k]
node = inputObject[key]
if (isObject(node)) {
nullPrune(node, {
objectKey: key,
parentObject: inputObject
})
} else if (node == null) {
delete inputObject[key]
}
}
if (parentObject && ownKeys(inputObject).length === 0) {
delete parentObject[objectKey]
}
}
return function (inputObject) {
if (!isObject(inputObject)) {
return inputObject
}
nullPrune(inputObject, {})
return inputObject
}
})