[
{
"id": 35, "code": "110100", "name": "北京市", "type": 1, "regions": [ { "id": 373, "code": "110101", "name": "东城区", "type": 2, "regions": [], "latitude": 0, "longitude": 0 }, { "id": 373, "code": "110101", "name": "西城区", "type": 2, "regions": [], "latitude": 0, "longitude": 0 }], "latitude": 0, "longitude": 0 }, { "id": 36, "code": "120100", "name": "天津市", "type": 1, "regions": [ { "id": 389, "code": "120101", "name": "和平区", "type": 2, "regions": [], "latitude": 0, "longitude": 0 }], "latitude": 0, "longitude": 0 }, { "id": 37, "code": "130100", "name": "石家庄市", "type": 1, "regions": [ { "id": 405, "code": "130102", "name": "长安区", "type": 2, "regions": [], "latitude": 0, "longitude": 0 }], "latitude": 0, "longitude": 0 }]
有一个这样的数组,我不知道怎么递归遍历返回出成为这样的数组形式
[{
text:'北京市',
value:'北京市', children:[ { text:'东城区',
value:'东城区' } ] },{ text:'北京市',
value:'北京市', children:[ { text:'东城区',
value:'东城区' }, { text:'西城区',
value:'西城区' } ] }]
请问一下怎么写这个递归的函数?
var newarr = [];
for(var i=0;i<arr.length;i++){
newarr[i] = {
text : arr[i].name,
value : arr[i].name,
childern : [{
text : arr[i].regions[0].name,
value : arr[i].regions[0].name
}]
};
}
console.log(newarr);
整理一下:
function abc(arr) {
var arr1 = [];
for(var i = 0, l = arr.length; i < l; i++) {
arr1[i] = {
text: arr[i].name,
value: arr[i].name,
children: [{
text: arr[i].regions[0].name,
value: arr[i].regions[0].name
}]
}
}
return arr1;
}
var a = abc(arr);
console.log(a)
这是我在:https://segmentfault.com/q/1010000008641909?_ea=1702980上看到的一个问题