Вы можете использовать следующую функцию:
const restructure = (nodes, filter) => nodes.reduce(
(acc, node) => {
const children = restructure(node.children, filter);
return acc.concat(
filter(node)
? {...node, children}
: children
);
},
[]
);
, которая принимает filter
в качестве функции. Это позволяет вам решить, как фильтровать, например:
const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);
Или:
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));
Единственное отличие вашего кода выше в том, что dataToFilter
уже должен быть массивом узлов (см. полный фрагмент кода ниже).
const restructure = (nodes, filter) => nodes.reduce(
(acc, node) => {
const children = restructure(node.children, filter);
return acc.concat(
filter(node)
? {...node, children}
: children
);
},
[]
);
const dataToFilter = [{
'tagPath': '/../../tagPath-1',
'children': [{
'tagPath': '/../../tagPath-1-1',
'children': [{
'tagPath': '/../../tagPath-1-2',
'kind': 'Y',
'children': [{
'tagPath': '/../../tagPath-1-3.1',
'kind': 'X',
'children': []
}, {
'tagPath': '/../../tagPath-1.3.2',
'kind': 'X',
'children': [{
'tagPath': '/../../tagPath-1.3',
'kind': 'Y',
'children': []
}]
}]
}, {
'kind': 'Y',
'children': []
}],
'kind': 'X',
}],
'kind': 'Y',
}];
const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);
const xOnly = restructure(dataToFilter, node => 'X' === node.kind);
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));
console.log(yOnly);
console.log(xOnly);
console.log(yAndX);