I have an array of objects as following
[
0: {department_ID: 6, department_Name: "Management", section_ID: 12, section_Name: "General Management", employee_ID: 1, …}
1: {department_ID: 6, department_Name: "Management", section_ID: 12, section_Name: "General Management", employee_ID: 2, …}
2: {department_ID: 1, department_Name: "HR & Admin", section_ID: 20, section_Name: "HR and Admin", employee_ID: 90, …}
...
]
What I want to achieve is to group values in an array by order same department_ID > same section_ID and finally employee data like this
[
{
department_ID: 6,
department_Name: "Management",
children: [
{
section_ID: 12,
section_Name: "General Management",
children: [
{
employee_ID: 1,
employee_Name: "",
},
{
employee_ID: 2,
employee_Name: "",
},
],
},
],
},
{
department_ID: 1,
department_Name: "HR & Admin",
children: [
{
section_ID: 20,
section_Name: "HR and Admin",
children: [
{
employee_ID: 90,
employee_Name: "",
},
],
},
],
},
];
I've tried
function getUnique() {
var hashObject = {};
let obj = {};
treeviewApiValues.forEach(function (elem) {
var key = elem.department_ID;
if (hashObject[key]) {
hashObject[key] = {
id: elem.department_ID,
name: elem.department_Name,
children: checkSectionID(elem),
};
} else {
hashObject[key] = {
id: elem.department_ID,
name: elem.department_Name,
children: checkSectionID(elem),
};
}
});
function checkSectionID(elem) {
const key = elem.department_ID;
if (obj[key]) {
obj[key].push({
id: elem.section_ID,
name: elem.section_Name,
});
} else {
obj[key] = [
{
id: elem.section_ID,
name: elem.section_Name,
},
];
}
var desiredArray2 = Object.values(obj);
return desiredArray2;
}
var desiredArray = Object.values(hashObject);
}
This is a messy function, but I get
[
0: {department_ID: 1, department_Name: "HR & Admin", children: Array(7)}
1: {department_ID: 2, department_Name: "ELV Systems Installation & Service", children: Array(7)}
]
Children array is something wrong and not having array of same department_ID and I also need to get the employee data under same section_ID. If anyone could help me, i would be so much appreciated.
Full code can be found here https://codesandbox.io/s/gracious-voice-bbmsy?file=/src/App.js