I have the following array object. I would like to flatten the array to get only object with names containing 'Martin'
Source Array:
[
{
"id": 302,
"name": "David Martin",
"subordinates": [
{
"id": 265,
"name": "Martin Regan",
},
{
"id": 300,
"name": "William Baker",
},
{
"id": 301,
"name": "Anthony Mazzarino",
"subordinates": [
{
"id": 11245,
"name": "Martin Lozano",
}
]
}
]
},
{
"id": 10441,
"name": "Martin Delage De Luget"
}
]
Expected Result:
[
{
"id": 302,
"userGuid": "66d6fd24-0e22-4384-9181-f72c4e81cefd",
"name": "David Martin"
},
{
"id": 265,
"name": "Martin Regan",
},
{
"id": 11245,
"name": "Martin Lozano",
}
]
Recursion is always an easy solution in these kind of cases:
flatElements = (array, keyword) => {
// Recursive function
const traverse = (subArray, acc = []) => {
subArray.forEach(element => {
const {id, name, subordinates} = element;
// If object with certain condition push it in the resulting acc
if (element.name.contains(keyword)) {
acc.push({id, name});
}
// If subordinates exist, traverse them deeply
if (subordinates) {
traverse(subordinates, acc);
}
});
// Return accumulator
return acc;
}
return traverse(array, []);
}