I currently have this array which repeats recursively:
JavaScript
x
18
18
1
[
2
{
3
"Name": "Test",
4
"Children": [
5
{
6
"Name": "Id",
7
"Property": "Placeholder",
8
"Children": [
9
{
10
"Name": "Child Id",
11
"Property": "Placeholder",
12
"Children": null
13
}
14
]
15
}
16
}
17
]
18
To get the structure I want I currently have this:
JavaScript
1
10
10
1
const fixed = data.map(item => item = {
2
data: {
3
name: item.Name,
4
},
5
children: item.Children.map(child => child = {
6
name: child.Name,
7
})
8
}
9
)
10
Is there a way to repeat my initial array.map recursively for each child array?
Advertisement
Answer
One possible solution, based on the output I believe you want:
JavaScript
1
36
36
1
const array = [{
2
"Name": "Test",
3
"Children": [{
4
"Name": "Id",
5
"Property": "Placeholder",
6
"Children": [{
7
"Name": "Child Id 1",
8
"Property": "Placeholder",
9
"Children": null
10
}, {
11
"Name": "Child Id 2",
12
"Property": "Placeholder",
13
"Children": [{
14
"Name": "Child Id 3",
15
"Property": "Placeholder",
16
"Children": null
17
}]
18
}]
19
}]
20
}];
21
22
23
const map = (arr) => {
24
return arr ? arr.map(fix) : null;
25
}
26
27
const fix = (item) => {
28
return {
29
data: {
30
name: item.Name
31
},
32
children: map(item.Children),
33
};
34
}
35
36
console.log(map(array))
Or as suggested below, use shortands:
JavaScript
1
9
1
const map = arr => arr ? arr.map(fix) : null;
2
3
const fix = item => ({
4
data: {
5
name: item.Name
6
},
7
children: map(item.Children),
8
});
9