这样一个需求,这样的JSON,如果当前的对象下面的type为object,则需要用一个新的对象items包裹里面的层级。例如vardataPre={"name":{"type":"string","desc":"病人姓名","testData":"张三李四","sex":{"type":"object",//这里的type为object"desc":"性别",//如果同级的type为object,需要删除这个字段"testData":"男",//如果同级的type为object,需要删除这个字段"city":{"type":"string","desc":"城市","testData":"杭州"},"street":{"type":"string","desc":"街道","testData":"浦口街道"}}},"order":{"type":"string","desc":"订单","testData":"名称"}}修改成这样的,这个JSON对象总共有三级,可能会有很对数据,大概数据结构就是这样vardataHandle={"name":{"type":"string","desc":"病人姓名","testData":"张三李四","sex":{"type":"object","items"{//这里的为新添加的对象"city":{"type":"string","desc":"城市","testData":"杭州"},"street":{"type":"string","desc":"街道","testData":"浦口街道"}}}},"order":{"type":"string","desc":"订单","testData":"名称"}}谢谢!
2 回答
手掌心
TA贡献1942条经验 获得超3个赞
functiongenerate(obj){let_obj={};if(obj['type']&&obj['type']==='object'){letitems={},flag=false;Object.entries(obj).forEach(([key,value])=>{if(key==='type'){_obj[key]=value}elseif(typeof(value)==='object'){flag=true;items[key]=generate(value);}})if(flag){_obj['items']=items;}}else{Object.entries(obj).forEach(([key,value])=>{if(typeof(value)!=='object'){_obj[key]=value}else{_obj[key]=generate(value);}})}return_obj}
HUH函数
TA贡献1836条经验 获得超4个赞
functiontransform(source){varfilterKeys=["desc","testData"];if(source===null||typeofsource!=="object"){returnsource;}Object.keys(source).forEach(key=>{letitem=source[key];if(item&&typeofitem==="object"&&item.type==="object"){filterKeys.forEach(filter=>{deleteitem[filter];});letkeys=Object.keys(item),grouped={};keys.forEach(subKey=>{if(subKey!=="type"){grouped[subKey]=item[subKey];deleteitem[subKey];}});item.items=transform(grouped);}else{source[key]=transform(item);}});returnsource;}
添加回答
举报
0/150
提交
取消