Headcount Under Nested Json
I am trying to get the employee count under a manger and trying to add it If Manager=True from the below nested JSON [{ 'name': 'Wendeline', 'IsManager': 'TRUE', 'children': [{
Solution 1:
We can get the DirectChildrencount
using the children.length
property.
Further, we will make use of Array.prototype.reduce() to calculate TBDCount
and EmployeeCount
. We will use Array.prototype.map() to recursively iterate over the children
.
Here is the code snippet that manipulates the input to obtain required output. Suppose a
is your array:
const a = [ /* */ ]
consttransform = x => {
if (x.IsManager === "TRUE") {
const child = x.children.reduce(
(acc, curr) => {
acc.tbd = curr.EmployeeNumber === "TBD" ? acc.tbd + 1 : acc.tbd;
acc.fte = curr.EmployeeNumber !== "TBD" ? acc.fte + 1 : acc.fte;
return acc;
},
{ tbd: 0, fte: 0 }
);
x.count = `${x.children.length}/${child.tbd}TBD/${child.fte}FTE`;
}
x.children = x.children.map(transform);
return x;
};
const b = a.map(transform);
console.log(b);
Because we are assigning output of map
to x.children
, you can also do:
a = [/* */];
a.forEach(transform);
console.log(a)
Post a Comment for "Headcount Under Nested Json"