Take a look at this snapshot of my JSON data.
const info = [{
"employees": [
{
"employee": [
{
"name": "Jon",
"surname": "Smith",
"leaveRequest": [
{
"id": "3000",
"approver": "Terry"
}
]
}],
},
{
"employee": [
{
"name": "Mike",
"surname": "Jones",
"leaveRequest": [
{
"id": "1700",
"approver": "Mary"
}
]
},
]
}
]
}];
I'm aiming to establish a way to search by ID within all leave requests and retrieve the employee's name and surname.
For example, if I input the ID "3000", I expect to get an object with the values ["name": "Jon", "surname": "Smith"]
I attempted to apply the solution shared in: How to get immediate parent Id of the child id in array of nested json Object?
This is the implementation I tried:
const locateEmployee = (arr, id) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
return [];
}
else if (arr[i].employee && arr[i].employee.length) {
const result = locateEmployee(arr[i].employee, id);
if (result !== false) {
if (result.length == 0)
result.push({"name": arr[i].name, "surname": arr[i].surname});
return result;
}
}
}
return false;
};
console.log(locateEmployee(info, "3000"))
However, the approach in that discussion assumes each child node has the same key 'children', which doesn't suit my situation. I would need to reorganize my JSON structure to follow:
employee
employee
employee
id
Yet, this restructuring isn't logical for my use case. How can I effectively search by ID within all leave requests and fetch the employee's name and surname from the direct parent?