test.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. </body>
  10. <script>
  11. let arr = [
  12. { comment_id: 1, user_id: 43, comment_date: "04-23", comment_content: "蜡笔小新很好看!", parent_id: null },
  13. { comment_id: 2, user_id: 19, comment_date: "04-24", comment_content: "还不错哦!很好看", parent_id: null },
  14. { comment_id: 3, user_id: 17, comment_date: "04-25", comment_content: "我也感觉蜡笔小新很好看", parent_id: "1" },
  15. { comment_id: 4, user_id: 14, comment_date: "04-26", comment_content: "我感觉机器猫更好看一点", parent_id: "3" },
  16. { comment_id: 5, user_id: 13, comment_date: "04-27", comment_content: "好看,已三连!", parent_id: null },
  17. { comment_id: 6, user_id: 21, comment_date: "04-26", comment_content: "你是机器猫的粉丝吗", parent_id: "4" },
  18. { comment_id: 7, user_id: 14, comment_date: "04-27", comment_content: "是的,我是机器猫的粉丝", parent_id: "6" },
  19. { comment_id: 8, user_id: 23, comment_date: "04-27", comment_content: "我更喜欢白嫖!", parent_id: "5" },
  20. { comment_id: 9, user_id: 25, comment_date: "04-28", comment_content: "你个白嫖怪", parent_id: "8" }
  21. ]
  22. function fn(temp) {
  23. let arr1 = []
  24. for (var i = 0; i < arr.length; i++) {
  25. if (arr[i].parent_id == temp) {
  26. arr1.push(arr[i])
  27. arr[i].child = fn(arr[i].comment_id)
  28. }
  29. }
  30. return arr1
  31. }
  32. const res = fn(null)
  33. console.log(res);
  34. // console.log(arr1);
  35. // [
  36. // { comment_id: 1, user_id: 43, comment_date: "04-23", comment_content: "蜡笔小新很好看!", parent_id: null,child:[
  37. // { comment_id: 3, user_id: 17, comment_date: "04-25", comment_content: "我也感觉蜡笔小新很好看", parent_id: "1" ,child:[
  38. // { comment_id: 4, user_id: 14, comment_date: "04-26", comment_content: "我感觉机器猫更好看一点", parent_id: "3" ,child:[
  39. // { comment_id: 6, user_id: 21, comment_date: "04-26", comment_content: "你是机器猫的粉丝吗", parent_id: "4" },
  40. // ]},
  41. // ]},
  42. // ]}
  43. // ]
  44. </script>
  45. </html>