I have a JSON object called "data" in React that contains nested objects, resembling a hierarchical directory or file structure with an arbitrary number of layers.
const data = {
"item1": {
"item1.1": {
"item1.1.1": {
"item1.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "ERROR"
}
}
},
"item1.2": {
"item1.2.1": {
"item1.2.1.1": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "WARNING"
}
}
}
},
"item2": {
"item2.1": {
"item2.1.1": {
"item2.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "WARNING"
}
},
"item2.1.2": {
"item2.1.2.1": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "OK"
},
"item2.1.2.2": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "WARNING"
}
}
}
},
"item3": {
"item3.1": {
"item3.1.1": {
"item3.1.1.1": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "OK"
}
},
"item3.1.2": {
"attr1": [],
"attr2": "",
"attr3": [],
"status" : "ERROR"
}
}
}
}
I'm attempting to create a function that filters the object based on the status value.
For instance, calling getStatuses(data, "ERROR") should return a list of all objects with the status set to "ERROR". The expected result would be:
{"item1.1.1.1": {"attr1": [], "attr2": "", "attr3": [], "status" : "ERROR"},
"item3.1.2": {"attr1": [], "attr2": "", "attr3": [], "status" : "ERROR"}
}
My approach involves recursively looping through the data and adding matching objects to a list, but I seem to encounter issues as the results aren't as expected.
const getStatuses= (obj, status) => {
let result = [];
if (obj.status === status) {
result.push(obj)
}
Object.entries(obj).forEach(([, value]) => {
//if object is not a leaf node
if (value !== null && !Array.isArray(value) && typeof value === 'object') {
getStatuses(value, status); //recursive call to dive into another layer
}
});
}