I want to write a function that takes a nested json object and writes a path array in each of objects that denote the "path" or hierarchy of the object itself. the path array should be populated by the id of the parent nodes. the limits array objects should have a path and since they don't have an id, an enumarated key is given to them based on the index in that array. my attempt is below however I am not getting the correct path at certain nth levels down.
let nestedObject = {
"name":"bob",
"root_rule":{
"id":0,
"limits":[
{
"value":0
}
],
"rules":[
{
"id":15,
"limits":[
],
"rules":[
]
},
{
"id":16,
"limits":[
{
"value":25000000
},
{
"value":50001
},
{
"value":25000001
}
],
"rules":[
{
"id":20,
"limits":[
{
"value":0
}
],
"rules":[
{
"id":21,
"limits":[
],
"rules":[
]
}
]
}
]
}
]
}
}
function encodeNestedPath(nestedJson, pathList, type, parent = null) {
// process rood node
if ((typeof nestedJson) == 'object') {
if(nestedJson && nestedJson.condition && nestedJson.condition.name === 'ROOT') {
nestedJson['path'] = [String(nestedJson['id'])];
}
if(nestedJson.limits) {
encodeNestedPath(nestedJson.limits, nestedJson['path'], 'limits', nestedJson['id']);
}
if(nestedJson.rules) {
encodeNestedPath(nestedJson.rules, nestedJson['path'], 'rules', nestedJson['id']);
}
}
// traverse children nodes
if (Array.isArray(nestedJson)) {
for (const [i, element] of nestedJson.entries()) {
element['path'] = [];
if(String(parent)) {
element['path'].push(String(parent))
}
let parentId
if(!element.hasOwnProperty('id')) {
element['path'].push(type+'_'+i)
pathList = null
} else {
element['path'].push(String(element['id']))
parentId = element['id']
}
if(element.limits) {
encodeNestedPath(element.limits, element['path'], 'limits', parentId);
}
if(element.rules) {
encodeNestedPath(element.rules, element['path'], 'rules', parentId);
}
}
}
}
encodeNestedPath(nestedObject['root_rule'], null, null, null)
console.log(JSON.stringify(nestedObject['root_rule'], null, 4))
Desiring output is like this.
