I have written this function but I am not so proud on it. I could use some help refactoring it.
Would recursion improve my code?
Data sample.
{
"Name":"test2",
"DepartmentUnitId":"test",
"ParentDepartmentUnitId":"test",
"NestedDepartments":[
{
"Name":"test2",
"DepartmentUnitId":"test",
"ParentDepartmentUnitId":"test",
"NestedDepartments":[]
},
{
"Name":"test2",
"DepartmentUnitId":"test",
"ParentDepartmentUnitId":"test",
"NestedDepartments":[]
}
]
}
JS:
function indentDepartments(departments, model) {
var indentedDepartments = [];
_.each(departments, function (department) {
indentedDepartments.push(buildDepartment(department, 0));
_.each(department.NestedDepartments, function (lv1Department) {
indentedDepartments.push(buildDepartment(lv1Department, 1));
_.each(lv1Department.NestedDepartments, function (lv2Department) {
indentedDepartments.push(buildDepartment(lv2Department, 2));
});
});
});
function buildDepartment(data, level) {
department = _.pick(data, 'DepartmentUnitId', 'ParentDepartmentUnitId');
name = _.times(level, function () { return '-'; }).join('') + data.Name;
_.extend(department, { Name: name });
return department;
}
model.parentDepartments(indentedDepartments);
}
Edit: Nested array can go 2 levels deep, but I wouldn't mind making this function more scalable.
NestedDepartments
? \$\endgroup\$