consttarget=[{"title":"人物数据","value":"","children":[{"title":"本市常驻人员","value":"361,123","children":null},{"title":"本市暂住人员","value":"361,123","children":null},{"title":"本市流动人员","value":"361,123","children":null},{"title":"往来过省人员","value":"361,123","children":[{"title":"出境申请人员","value":"361,123","children":null},{"title":"火车过省人员","value":"361,123","children":null}]}]},{"title":"车辆数据","value":"","children":null}]有如下数据结构,如何将里面title都改为name呢,用递归的写法怎么也绕不过来,请高手指教。。
2 回答
守着一只汪
TA贡献1872条经验 获得超3个赞
分两种情况递归,数组和对象replace(target);functionreplace(target){if(targetinstanceofArray){target.forEach(element=>{replace(element);});}elseif(target&&typeoftarget==="object"){Object.keys(target).forEach(key=>{if(target[key]&&typeoftarget[key]==="object"){replace(target[key]);}if(key==='title'){target['name']=target[key];deletetarget['title'];}});}else{return;}}console.log(target);
添加回答
举报
0/150
提交
取消