When extracting JSON data from a table, the format typically resembles the following simplified structure:
https://i.sstatic.net/eqfXM.png
The JSON format obtained might look like this:
const myObjOriginal = {
"rows": [{
"name": "row 1",
"cells": [{
"name": "level 1",
"id": 1
}, {
"name": "first level 2",
"id": 2
}, {
"name": "endpoint 1",
"id": 4
}]
},
{
"name": "row 2",
"cells": [{
"name": "level 1",
"id": 1
},
{
"name": "first level 2",
"id": 2
},
{
"name": "endpoint 2",
"id": 5
}]
},
{
"name": "row 3",
"cells": [{
"name": "level 1",
"id": 1
},
{
"name": "second level 2",
"id": 3
},
{
"name": "endpoint 3",
"id": 6
}]
}]
};
The task at hand is to transform this structure into a tree layout instead of a tabular one, producing output similar to this:
const goalObject = [{
"name": "level 1",
"id": 2,
"children": [{
"name": "first level 2",
"id": 2,
"children": [{
"name": "endpoint 1",
"id": 4
}, {
"name": "endpoint 2",
"id": 5
}]
}, {
"name": "second level 2",
"id": 3,
"children": [{
"name": "endpoint 3",
"id": 6
}]
}]
}];
Various methods like map, reduce, filter, loops, and forEach have been attempted without success. It's clear that implementing a recursive function is necessary, but achieving this has proven challenging.
An attempt was made using the code snippet below, although it's recognized as incorrect:
function getChildrenOfCurrentItem(rowIndex = 0, cellIndex = 0) {
let current = {};
let myObj = {};
for(let i = 0; i < myCopy.rows.length; i++){
next = myCopy.rows[i].cells[cellIndex];
const cells = myCopy.rows[i].cells;
const isSame = compareObjects(current, next);
if(!isSame){
current = next;
myObj.item = current;
for(let j = 0; j < cells.length; j++){
let cell = cells[j];
console.log('cell', cell);
}
}
console.log('myObj', myObj);
if(cellIndex < max) {
getChildrenOfCurrentItem(rowIndex, cellIndex);
}
rowIndex++;
}
return myObj;
}