I have an array of objects with parentId and sort values that I'd like to put into an array with nested 'children' and sorted appropriately.
For example, here's the data:
[{
id: 1,
sort: 2,
parentId: null,
name: 'A'
}, {
id: 2,
sort: 1,
parentId: 1,
name: 'A.1'
}, {
id: 3
sort: 2,
parentId: 1,
name: 'A.2'
}, {
id: 4,
sort: 1,
parentId: null,
name: 'B'
}]
The way I'd like to transform this would be such as:
[{
id: 4,
sort: 1,
parentId: null,
name: 'B',
children: []
}, {
id: 1,
sort: 2,
parentId: null,
name: 'A',
children: [{
id: 2,
sort: 1,
parentId: 1,
name: 'A.1'
}, {
id: 3
sort: 2,
parentId: 1,
name: 'A.2'
}]
}]
This is sorted (id 4 being at the top, since sort is 1) and the children are nested and also sorted accordingly.
Any suggestions on a good way to do this? I can recursively loop through to apply children, but not sure how I can maintain sorting on this.
names one character long only? Is the first part of thenameonly alphabets as inA-Zor are there numbers and special characters?