I am looking to create a hierarchical object structure similar to the following:
record 1 {id, name, desc}
record 2 {id, name, desc}
record 3 {id, name, desc}
record 4 {id, name, desc}
This is a nested structure where record 1 acts as the parent and record 2 is its child, with subsequent records as children of their preceding ones.
I have researched various resources on stack overflow which recommend methods like push and put, but I am struggling to implement them correctly. Any assistance would be appreciated.
Objective:
{
"8b9e235c0fe412004e938fbce1050e0f": [
{
"name": "Parent 1",
"childs": [
"caf23c95db3110100cc4bd513996195d": {
"name": "Child of Parent 1",
"childs": [
"caf23c95db3110100cc4bd513996195d": {
"name": "Child of Child 2"
}
]
}
]
}
]
}
The order may not be correct, but the goal is to convert the given object into a nested one.
[
{
"name": "Level 2",
"childId": "caf23c95db3110100cc4bd513996195d",
"parentId": "8b9e235c0fe412004e938fbce1050e0f",
"description": null,
"level": 1
},
{
"name": "Level 3",
"childId": "c303f495db3110100cc4bd51399619b8",
"parentId": "caf23c95db3110100cc4bd513996195d",
"description": null,
"level": 2
},
{
"name": "Level 4",
"childId": "be133895db3110100cc4bd51399619ba",
"parentId": "c303f495db3110100cc4bd51399619b8",
"description": null,
"level": 3
},
{
"name": "Intrusion and Incident Response Standard Operating Procedure",
"id": "8b9e235c0fe412004e938fbce1050e0f",
"description": "blablalblablabab",
"level": 0
}
]
Using the code snippet below...
function hasChild(parent, level) {
var grProcessChild = new GlideRecord('sn_compliance_policy');
grProcessChild.addQuery('parent', parent);
grProcessChild.query();
while (grProcessChild.next()) {
var level = parseInt(level) + 1;
var child = {}; // object
child.name = grProcessChild.getValue('name');
child.childId = grProcessChild.getUniqueValue();
child.parentId = grProcessChild.getValue('parent');
child.description = grProcessChild.getValue('description');
child.level = level;
arrData.push(child);
hasChild(grProcessChild.getUniqueValue(), level);
}
}
var arrData = []; // array
var grProcess = new GlideRecord('sn_compliance_policy');
grProcess.addQuery('sys_id', '8b9e235c0fe412004e938fbce1050e0f');
grProcess.query();
while (grProcess.next()) {
var root = {}; // object
root.name = grProcess.getValue('name');
root.id = grProcess.getUniqueValue();
root.description = grProcess.getValue('description');
root.level = 0;
hasChild(grProcess.getUniqueValue(), root.level);
arrData.push(root);
}