-
Notifications
You must be signed in to change notification settings - Fork 2
/
walk-object-async.js
38 lines (35 loc) · 990 Bytes
/
walk-object-async.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
const isObject = require('is-pure-object')
module.exports = async function walkObjectAsync(root, fn) {
async function walk(obj, location = []) {
const keys = Object.keys(obj)
for (let key of keys) {
if (Array.isArray(obj[key])) {
for (let [ index, el ] of obj[key].entries()) {
await fn({
value: el,
key: `${key}:${index}`,
location: [...location, ...[key], ...[index]],
isLeaf: false
})
await walk(el, [...location, ...[key], ...[index]])
}
} else if (isObject(obj[key])) {
await fn({
value: obj[key],
key,
location: [...location, ...[key]],
isLeaf: false
})
await walk(obj[key], [...location, ...[key]])
} else {
await fn({
value: obj[key],
key,
location: [...location, ...[key]],
isLeaf: true
})
}
}
}
return await walk(root)
}