-
Notifications
You must be signed in to change notification settings - Fork 2
/
walk-object.js
47 lines (41 loc) · 1.16 KB
/
walk-object.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
const isObject = require('is-pure-object')
/**
* @param {object} root - The object to walk
* @param {function} fn - A function to call on each node
*/
module.exports = function walkObject(root, fn) {
function walk(obj, location = []) {
Object.keys(obj).forEach((key) => {
// Value is an array, call walk on each item in the array
if (Array.isArray(obj[key])) {
obj[key].forEach((el, j) => {
fn({
value: el,
key: `${key}:${j}`,
location: [...location, ...[key], ...[j]],
isLeaf: false
})
walk(el, [...location, ...[key], ...[j]])
})
// Value is an object, walk the keys of the object
} else if (isObject(obj[key])) {
fn({
value: obj[key],
key,
location: [...location, ...[key]],
isLeaf: false
})
walk(obj[key], [...location, ...[key]])
// We've reached a leaf node, call fn on the leaf with the location
} else {
fn({
value: obj[key],
key,
location: [...location, ...[key]],
isLeaf: true
})
}
})
}
walk(root)
}