Js array object, which matches the id of the object according to the same value of a field in the object.

var arr = [

]
    {
      "id": 1,
      "name": "1",
      "action": "",
      "type": 1,
      "parentId": 0,
      "icon": "icon"
    },
    {
      "id": 2,
      "name": "2",
      "action": "",
      "type": 1,
      "parentId": 0,
      "icon": "icon"
    },
    {
      "id": 3,
      "name": "3",
      "action": "",
      "type": 2,
      "parentId": 1,
      "icon": "icon"
    },
    {
      "id": 4,
      "name": "3",
      "action": "",
      "type": 2,
      "parentId": 2,
      "icon": "icon"
    }
  ]

Raw data, rendered as a level 2 menu, type is the level of the menu, 1 is the first level, 2 is the level 2
parentId is the associated field, for example, 0 is not associated, 1 is matched with the id of 1, and so on

the desired data format is

[
    {
      "id": 1,
      "name": "1",
      "action": "",
      "type": 1,
      "parentId": 0,
      "icon": "icon",
      "data":[
         {
          "id": 3,
          "name": "3",
          "action": "",
          "type": 2,
          "parentId": 1,
          "icon": "icon"
        }
      ]
    },
    {
      "id": 2,
      "name": "2",
      "action": "",
      "type": 1,
      "parentId": 0,
      "icon": "icon",
      "data":[
        {
          "id": 4,
          "name": "4",
          "action": "",
          "type": 2,
          "parentId": 2,
          "icon": "icon"
        },
        {
          "id": 5,
          "name": "5",
          "action": "",
          "type": 2,
          "parentId": 2,
          "icon": "icon"
        }
        //...
      ]
    }
  ]
  

Please help the bosses ~ Thank you-sharp-sharp-sharp

Jan.13,2022

if you are sure that there are only two layers, a simple traversal will be ok.
in order to speed up the operation, you can first convert the arr array to object,key and use id

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37a70-2c0a4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37a70-2c0a4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?