forked from conorhastings/whitelist-object
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whitelist.js
50 lines (45 loc) · 1.26 KB
/
whitelist.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
var whitelist = function(object, whitelist, shallow){
shallow = shallow === undefined ? false : shallow;
return objectReducer(object, whitelist, shallow);
}
function objectReducer(object, whitelist, shallow) {
var keys = Object.keys(object);
var reducedObject = keys.reduce(function(newObject, key) {
if(whitelist.indexOf(key) !== -1) {
if(valueIsObject(object[key]) && !shallow) {
newObject[key] = objectReducer(object[key], whitelist, false);
}
else if(valueIsArray(object[key]) && !shallow) {
newObject[key] = reduceArrayOfPotentialObjects(object[key], whitelist);
}
else {
newObject[key] = object[key];
}
}
return newObject;
}, {});
return reducedObject;
}
function valueIsObject(value) {
return typeof value === "object" && !Array.isArray(value);
}
function valueIsArray(value) {
return Array.isArray(value);
}
function reduceArrayOfPotentialObjects(array, whitelist) {
var newArray = array.map(function(item){
var returnValue = null;
if(valueIsObject(item)){
returnValue = objectReducer(item, whitelist, false);
}
else if(valueIsArray(item)){
returnValue = reduceArrayOfPotentialObjects(item, whitelist);
}
else {
returnValue = item;
}
return returnValue;
});
return newArray;
}
module.exports = whitelist;