React中递归过滤嵌套JSON对象,按status筛选目标数据
问题:递归过滤嵌套JSON对象中的指定status项
我在React项目中有一个名为data的嵌套JSON对象,结构类似目录/文件结构,层级数量不固定,具体数据如下:
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" } } } }
我需要编写一个函数,根据status值过滤该对象。例如调用getStatuses(data, "ERROR")时,需返回所有status为"ERROR"的对象,预期返回结果如下:
{"item1.1.1.1": {"attr1": [], "attr2": "", "attr3": [], "status" : "ERROR"}, "item3.1.2": {"attr1": [],"attr2": "", "attr3": [], "status" : "ERROR"} }
我的思路是通过递归遍历数据,将匹配的对象存入集合,但当前编写的递归函数逻辑存在缺陷,无法得到正确结果,代码如下:
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 } }); }
内容的提问来源于stack exchange,提问作者Mark Yu
相关产品推荐
相关产品推荐

