-
Notifications
You must be signed in to change notification settings - Fork 0
/
drilldown.js
57 lines (51 loc) · 2.29 KB
/
drilldown.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
angular.module("aa.service.drilldown", [])
.factory("Drilldown", function($rootScope, $timeout) {
// Factory to assist with drilling down through possibly missing
// structures, to avoid "x && x.y && x.y.z" tests.
// Returns the default (or undefinded if not supplied) if the given
// path does not exist.
var log = function(message, level) { console[level](message); },
Drilldown = function Drilldown(parent, path, defaults) {
if (typeof path === "string") {
path = path.split(".");
}
var child = parent,
stringParent = parent,
hitArray = false,
realKey = null;
path.forEach(function(key, index, path) {
if (!hitArray) {
if (key.substr(-2) === "[]") {
hitArray = true;
realKey = key.slice(0, -2);
nextChild = [];
if (Array.isArray(child[realKey])) {
child[realKey].forEach(function(subchild) {
nextChild.push(
Drilldown(subchild, path.slice(index + 1), defaults)
);
});
child = nextChild;
} else {
child = undefined;
}
} else {
child = (
child && typeof child[key] !== "undefined" ?
child[key] :
undefined
);
}
}
});
if (typeof child === "undefined") {
try {
stringParent = JSON.stringify(parent);
} catch (e) {}
log("Could not drilldown to find '" + path.join(".") + "' in " + stringParent, "debug");
child = defaults;
}
return child;
};
return Drilldown;
});