Вы можете написать рекурсивную функцию для реструктуризации данных.
const a = [[
'fun', 'legal', 'adventure',
], [
'fun', 'legal', 'movie',
], [
'fun', 'legal', 'm&m'
], [
'fun', 'frowned upon', 'rec stuff'
], [
'fun', 'frowned upon', 'religius views'
]];
let t = [];
const addLeaf = (array) => {
if (!array || !array.length) return;
let temp = { name: array[0], children: [] };
if (array.length > 1) {
temp.children = [addLeaf(array.slice(1))];
}
return temp;
};
const addToTree = (tree, array) => {
if (!array || !array.length) return [];
const branchIndex = tree.findIndex(entry => entry.name === array[0]);
if (branchIndex !== -1) {
tree[branchIndex].children = [...addToTree(tree[branchIndex].children, array.slice(1))];
} else {
tree = [...tree, addLeaf(array)];
}
return tree;
};
a.forEach((entry) => {
t = addToTree(t, entry);
});
console.log(JSON.stringify(t, null, 2))