I’m iterating through a JS object (obj) and would like to retrieve the parent property of a property. E.g. if k is ‘v9’. Something like k.parent would return ‘c’ and k.parent.parent would return ‘b’. Of course, the syntax is different and that’s what I’m looking for
JavaScript
x
44
44
1
function iterate(o) {
2
3
Object.keys(o).forEach(function (k) {
4
5
if (o[k] !== null && typeof o[k] === 'object') {
6
iterate(o[k]);
7
return;
8
}
9
if (typeof o[k] === 'boolean') {
10
11
// e.g. k is 'v9'. How to get its parent properties?
12
// like k.parent would return 'c' and k.parent.parent would return 'b'
13
14
}
15
});
16
17
}
18
19
20
const obj = {
21
22
a: {
23
'v1': true,
24
'v2': true,
25
'v3': false
26
},
27
28
b: {
29
'v4': false,
30
'v5': true,
31
'v6': false,
32
33
34
c: {
35
'v7': false,
36
'v8': true,
37
'v9': false
38
}
39
}
40
41
}
42
43
iterate(obj);
44
Advertisement
Answer
an idea can be to store the parent key as a parameter of iterate function
JavaScript
1
42
42
1
function iterate(o, parentKey) {
2
3
Object.keys(o).forEach(function (k) {
4
5
if (o[k] !== null && typeof o[k] === 'object') {
6
iterate(o[k], k);
7
return;
8
}
9
if (typeof o[k] === 'boolean') {
10
console.log(k);
11
console.log(parentKey);
12
13
}
14
});
15
16
}
17
18
19
const obj = {
20
21
a: {
22
'v1': true,
23
'v2': true,
24
'v3': false
25
},
26
27
b: {
28
'v4': false,
29
'v5': true,
30
'v6': false,
31
32
33
c: {
34
'v7': false,
35
'v8': true,
36
'v9': false
37
}
38
}
39
40
}
41
42
iterate(obj);
Another idea can be to stored a structure fill at each iterate step if there is a parent to the current object use recursive behavior to fill it
JavaScript
1
46
46
1
function iterate(o, parent) {
2
3
Object.keys(o).forEach(function (k) {
4
5
if (o[k] !== null && typeof o[k] === 'object') {
6
const nextParent = { name: k };
7
if (parent.name) {
8
nextParent.parent = parent;
9
}
10
iterate(o[k], nextParent);
11
return;
12
}
13
if (typeof o[k] === 'boolean') {
14
console.log(k);
15
console.log(parent);
16
17
}
18
});
19
20
}
21
22
23
const obj = {
24
25
a: {
26
'v1': true,
27
'v2': true,
28
'v3': false
29
},
30
31
b: {
32
'v4': false,
33
'v5': true,
34
'v6': false,
35
36
37
c: {
38
'v7': false,
39
'v8': true,
40
'v9': false
41
}
42
}
43
44
}
45
46
iterate(obj, {});