I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array.
Issue: The code seems to enter the first if statement correctly, but the updated result is not being returned in the end. Instead, the input array of objects is always returned. What could be causing this problem?
FUNCTION:
export function findChild(array: any, id: string): array {
return array.map((node) => {
if (node.id === id) {
return { ...node, status: 'Activated' };
} else {
if (node.children?.length) {
findChild(node.children, id);
}
}
return node;
});
}
Plain JS
function findChild(array, id) {
return array.map((node) => {
if (node.id === id) {
return { ...node, status: 'Activated' };
} else {
if (node.children?.length) {
findChild(node.children, id);
}
}
return node;
});
}
findChild(input,7)
console.log(input)
**INPUT** This is just an example of input. The array of objects have multiple children and I have to go through all ids to check the condition and then update the value of status
<script>
let input = [{
id: '1',
amt: '30',
status: 'Active',
children: [{
id: 'SG2',
amt: '305',
status: 'Active',
},
{
id: '5',
amt: '30',
status: 'Active',
children: [],
},
],
},
{
id: '6',
amt: '307',
status: 'Active',
children: [],
},
{
id: '7',
amt: '40',
status: 'Inactive',
children: [{
id: '7',
amt: '40',
status: 'Inactive',
children: []
}],
},
{
id: '8',
amt: '100',
status: 'Dead',
children: [],
},
];
</script>