I have a JSON object "data" in React that has other objects nested inside it, think of it as a directory/ file structure where the number of layers is arbitrary.
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 trying to write a function that would filter the object based on the status value.
for example, getStatuses(data, "ERROR") will return a list of all the objects with the status being "ERROR". The expected return value is:
{"item1.1.1.1": {"attr1": [], "attr2": "", "attr3": [], "status" : "ERROR"},
"item3.1.2": {"attr1": [],"attr2": "", "attr3": [], "status" : "ERROR"}
}
My thoughts are that the function needs to loop through the data recursively and then push the matching objects into a list, but my logic seems to be flawed as I am not getting the right results.
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 in another layer
}
});
}