The JSON object below is currently formatted as follows:
{
"id": "jsonid",
"attributes": {
"personName": {
"id": "name1",
"group": "1.1"
},
"age": {
"id": "age1",
"group": "1.2.1"
},
"height": {
"id": "height1",
"group": "1.2.2.1"
}
}
}
In order to transform the attribute based on its group property into a hierarchical structure, it should be converted to the following format:
{
"id": "jsonid",
"attributes": {
"group1": {
"id": "group1",
"attributes": {
"group1.1": {
"id": "group1.1",
"attributes": {
"personName": {
"id": "name1"
}
}
},
"group1.2": {
"id": "group1.2",
"attributes": {
"group1.2.1": {
"id": "group1.2.1",
"attributes": {
"age": {
"id": "age1"
}
}
},
"group1.2.2": {
"id": "group1.2.2",
"attributes": {
"group1.2.2.1": {
"id": "1.2.2.1",
"attributes": {
"height": {
"id": "height1"
}
}
}
}
}
}
}
}
}
}
}
A function has been developed to handle all unique group values and break them into their possible combinations. For this specific JSON object, the potential combinations are: ["1", "1.1", "1.2", "1.2.1", "1.2.2", "1.2.2.1"]. The function iterates through these values:
allPossible.map((groupId, index, array) => {
createGroups(groupId, index, array);
});
The function used for this purpose is detailed below:
const createGroups = (groupId, index, array) => {
let groupObject = {
[groupId]: {
id: groupId,
attributes: {},
},
};
if (array[index + 1]) {
//If next element exists
if (groupId.length === array[index + 1].length) {
//To Check if the element should be in the same level
//e.g. group ids 1.1 and 1.2 should be under group id 1
let groupIdPrevious = array[index - 1];
groupObject[groupIdPrevious].attributes = createGroups(
array[index + 1],
index + 1,
array
);
}
groupObject[groupId].attributes = createGroups(
array[index + 1],
index + 1,
array
);
}
return groupObject;
};