js遍历数组并以特定形式展示
1 var arr = [{ 2 name: '1', 3 children: [{ 4 name: 2, 5 children: [] 6 }, 7 { 8 name: 3, 9 children: [{ 10 name: 4, 11 children: [{ 12 name: 5, 13 children: [] 14 }] 15 }] 16 }, 17 ] 18 }] 19 var newArr = []; 20 var parentName = null; 21 function fn(arr) { 22 for (var i = 0; i < arr.length; i++) { 23 if (arr[i].children.length !== 0) { 24 newArr.push({ 25 name: arr[i].name, 26 parentName: parentName 27 }) 28 parentName = arr[i].name 29 fn(arr[i].children) 30 } else { 31 newArr.push({ 32 name: arr[i].name, 33 parentName: parentName 34 }) 35 } 36 } 37 } 38 fn(arr) 39 console.log(newArr);