forked from yashprit/deep-find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (33 loc) · 837 Bytes
/
index.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
'use strict';
var deepFind = function(obj, path) {
if (((typeof obj !== "object") && (typeof obj !== "function")) || obj === null) {
return undefined;
}
if (typeof path === 'string') {
path = path.split('.');
}
if (!Array.isArray(path)) {
throw "path must be either an array or a string";
}
return path.reduce(function (o, part) {
var keys = part.match(/\[(.*?)\]/);
if (keys) {
var key = part.replace(keys[0], '');
if (!((typeof o === "undefined") || (o === null))) {
if (!((typeof o[key] === "undefined") || (o[key] === null))) {
return o[key][keys[1]];
} else {
return undefined;
}
} else {
return undefined;
}
}
if (!((typeof o === "undefined") || (o === null))) {
return o[part];
} else {
return undefined;
}
}, obj);
};
module.exports = deepFind;