As I traverse through a moderately complex JSON object, I gather and store all the values once I reach the end of the recursive loop
Here is an example of the object:
"if": {
"and": {
"or": {
"compare": [
{
"Hello": {
"constant": {
"string": "1"
}
},
},
{
"Hello": {
"constant": {
"string": "4"
}
}
}
]
},
"before": {
"Hello2": "12131",
"Hello": {
"constant": {
"datetime": "2001-01-01T00:00:00"
}
}
}
}
}
Next, I have defined a function:
function getAllGroups(obj)
{
for (var k in obj)
{
if (k === "hello") {
counter++;
array.push([]);
}
if (typeof obj[k] == "object" && obj[k] !== null) {
getAllGroups(obj[k]);
}
else
{
if (k !== "hello2") {
array[array.length - 1].push(obj[k]);
}
}
}
}
It may seem confusing at first, but essentially:
Whenever it encounters the key "hello", a new object is added to the empty array and filled with data. Each time it reaches the key "hello", a new object is created and populated with fresh data.
I faced difficulties in maintaining references to the parent objects. There are specific keys that need to be preserved like "and" & "or". For instance, after reaching the string: 1 which marks the end of the loop, I want to retain that it belongs to "or". Similarly, I wish to indicate that "or" is part of "and". Lastly, the datetime value should be associated with "and". Keep in mind that there can be multiple levels of nested "and" and "or".
EDIT:
I have updated the code to preserve the reference to the parent object. However, it currently only retains the reference to the last parent in the list, resulting in "datetime" being recognized as a child of "and" instead of "or"
function getAllGroups(obj)
{
for (var k in obj)
{
if (k === "and" || k === "or" || k === "not")
{
if (parentKey !== "") {
array.push([]);
array[array.length - 1].push(array[array.length - 1]['parent'] = parentKey);
parentKey = k + parentKeyNo;
parentKeyNo++;
array[array.length - 1].push(array[array.length - 1]['child'] = parentKey);
}
else {
parentKey = k + parentKeyNo;
parentKeyNo++;
array.push([]);
array[array.length - 1].push(array[array.length - 1]['child'] = parentKey);
}
}
if (k === "Hello") {
counter++;
array.push([]);
}
if (typeof obj[k] == "object" && obj[k] !== null) {
getAllGroups(obj[k]);
}
else
{
if (k !== "Hello2") {
if (array[array.length - 1].hasOwnProperty('parent'))
{
array[array.length - 1].push(obj[k]);
}
else
{
array[array.length - 1].push(array[array.length - 1]['parent'] = parentKey);
array[array.length - 1].push(obj[k]);
}
}
}
}
}
DESIRED OUTPUT:
[
[
{
"child": "and"
}
],
[
{
"parent": "and"
},
{
"child": "or"
}
],
[
{
"parent": "or"
},
{
"string": "1"
}
],
[
{
"parent": "or"
},
{
"string": "4"
}
],
[
{
"parent": "and"
},
{
"datetime": "2001-01-01T00:00:00"
}
]
]