Having some trouble with a code I'm trying to refactor, where I need to go over a 'tree' of items, filter some invalid items, and create a new array of filtered items which takes properties from both parent and child objects.
To demo the problem I made a quick snippet -
const items = [
{
name: 'Shirley Hardin',
isValid: true,
children: [
{
name: 'Mildred Mata',
isValid: true,
},
{
name: 'Christopher Herring',
isValid: false,
},
],
},
{
name: 'Tad M. Colbert',
isValid: false,
children: [
{
name: 'James J. Spencer',
isValid: true,
},
],
}
];
function toParentChildModel(parent, child) {
return {
parentName: parent.name,
childName: child.name,
};
}
function getValidChildParent(list) {
const validParentChild = [];
for (let i=0; i<list.length; i++) {
const parent = list[i];
if (parent.isValid) {
for (let j=0; j<parent.children.length; j++) {
const child = parent.children[j];
if (child.isValid) {
validParentChild.push(toParentChildModel(parent, child));
}
}
}
}
return validParentChild;
}
function print(list) {
console.log(list);
}
print(getValidChildParent(items));
The code can also be found at here
How would you refactor this code, specifically the 'getValidChildParent' function, in a functional way?