-
Notifications
You must be signed in to change notification settings - Fork 1
/
deep-search-json.js
77 lines (63 loc) · 2.25 KB
/
deep-search-json.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
68
69
70
71
72
73
74
75
76
77
// taken and modified from https://github.com/davidmehani/deep-search-JSON/blob/master/deep-search-JSON.js
// main modification is to keep iterating past the first key found, and the addition of adding the path to the callback
// deep object key search to find a key anywhere in an object and run a function on its parent (with support for async functions)
async function recursiveFind(obj, key, func, totalKeys) {
if (!totalKeys) totalKeys = []
if (!obj) return undefined;
if (typeof obj === "undefined") return undefined;
if (typeof obj !== "object") return undefined;
if (typeof obj[key] !== "undefined" && !obj.seen) {
if (func) await func(obj, newTotalKeys)
obj["seen"] = true
}
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (typeof obj[i] === "object") {
newTotalKeys = totalKeys.slice()
newTotalKeys.push(i)
await recursiveFind(obj[i], key, func, newTotalKeys);
}
}
}
if (!Array.isArray(obj)) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
if (typeof obj[keys[i]] === "object") {
newTotalKeys = totalKeys.slice()
newTotalKeys.push(keys[i])
await recursiveFind(obj[keys[i]], key, func, newTotalKeys);
}
}
}
return obj;
}
// clean up "seen" flag
function recursiveFindCleanup(obj) {
if (!obj) return undefined;
if (typeof obj === "undefined") return undefined;
if (typeof obj !== "object") return undefined;
if (typeof obj.seen !== "undefined") {
return delete obj.seen
}
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (typeof obj[i] === "object") {
recursiveFindCleanup(obj[i]);
}
}
}
if (!Array.isArray(obj)) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
if (typeof obj[keys[i]] === "object") {
recursiveFindCleanup(obj[keys[i]]);
}
}
}
return obj;
}
async function deepSearchJSON(obj, key, func) {
obj = JSON.parse(JSON.stringify(obj));
return recursiveFindCleanup(await recursiveFind(obj, key, func))
}
module.exports = deepSearchJSON;