猿问

萌新求教!改变树形结构里的键值各位有什么建议?

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呢,用递归的写法怎么也绕不过来,请高手指教。。
慕桂英3389331
浏览 287回答 2
2回答

守着一只汪

分两种情况递归,数组和对象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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答