Hi there, I need your help with recursion. I have a source array with objects and I need to regenerate it to result array view. Need to change some data structure.
I've tried to do that on my own but no results for now;(
Each element may have a parrent_id field, nesting can be infinite. How can I do that with recursion?
const source = [
{
id: 1,
title: 'title1',
alias: 'alias1',
parent_id: null
},
{
id: 2,
title: 'title2',
alias: 'alias2',
parent_id: null
},
{
id: 3,
title: 'title3',
alias: 'alias3',
parent_id: 2
},
{
id: 4,
title: 'title4',
alias: 'alias4',
parent_id: 2
},
{
id: 5,
title: 'title5',
alias: 'alias5',
parent_id: 4
},
{
id: 6,
title: 'title6',
alias: 'alias6',
parent_id: 4
}
];
const result = [
{
id: 1,
alias: 'alias',
title: 'root cat',
link: '/',
Icon: 'icon'
},
{
id: 2,
alias: 'alias',
title: 'Nested Pages',
Icon: 'icon',
items: [
{
id: 3,
alias: 'alias',
title: 'sub cat for Nested Pages'
},
{
id: 4,
alias: 'alias',
title: 'sub cat for Nested Pages',
items: [
{
id: 5,
alias: 'alias',
title: 'sub sub cat '
},
{
id: 6,
alias: 'alias',
title: 'Level 3'
}
]
}
]
}
];
Thnx in advance
P.S. Here is my code, it works just for one level nesting. How to solve it to use recursively?
let finArray = [];
const regenArray = (categories, parrent_id = null) => {
categories.map((el, index, array) => {
if (el.parent_id === parrent_id) {
finArray.push(el);
finArray[finArray.length - 1]['items'] = [];
categories.map(
(child_el, child_index, child_array) => {
if (el.id === child_el.parent_id) {
finArray[finArray.length - 1]['items'].push(
child_el
);
}
return false;
}
);
}
});
};
regenArray(categories);
console.log('finArray', finArray);