const target = [{ "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呢,用递归的写法怎么也绕不过来,请高手指教。。
1 回答
互换的青春
TA贡献1797条经验 获得超6个赞
分两种情况递归,数组和对象 replace(target);function replace(target) { if (target instanceof Array) { target.forEach(element => { replace(element); }); } else if (target && typeof target === "object") { Object.keys(target).forEach(key => { if (target[key] && typeof target[key] === "object") { replace(target[key]); } if (key === 'title') { target['name'] = target[key]; delete target['title']; } }); } else { return; } }console.log(target);
添加回答
举报
0/150
提交
取消