Ask a simple problem of converting js array to object.

var menuArray=[
    { id: 1, name: "", pid: 0 },
    { id: 2, name: "", pid: 1 },
    { id: 3, name: "UE", pid: 2 },
    { id: 4, name: "", pid: 2 },
    { id: 5, name: "", pid: 1 },
    { id: 6, name: "", pid: 5 },
    { id: 7, name: "Java", pid: 5 },
    { id: 8, name: "", pid: 1 },
    { id: 9, name: "1", pid: 8 },
    { id: 10, name: "2", pid: 8 }
];

convert the above data to the following data through operation

var data=[{
    id:0,
    name: "",
    item:[{
            id: 2,
            name: "",
            item: [
                {
                    id:3,
                    name: "UE"
                },
                {
                    id:4,
                    name: ""
                }
            ]
        },
        {
            id: 5,
            name: "",
            item: [
                {
                    id:6,
                    name: ""
                },
                {
                    id:7,
                    name: "Java"
                }
            ]
        },
        {
            id: 8,
            name: "",
            item: [
                {
                    id:9,
                    name: "1"
                },
                {
                    id:10,
                    name: "2"
                }
            ]
        }
    ]
}]

Note: data depth is uncertain

Mar.20,2021

var menuArray=[
    { id: 1, name: "", pid: 0 },
    { id: 2, name: "", pid: 1 },
    { id: 3, name: "UE", pid: 2 },
    { id: 4, name: "", pid: 2 },
    { id: 5, name: "", pid: 1 },
    { id: 6, name: "", pid: 5 },
    { id: 7, name: "Java", pid: 5 },
    { id: 8, name: "", pid: 1 },
    { id: 9, name: "1", pid: 8 },
    { id: 10, name: "2", pid: 8 }
];

let menuDict = menuArray.reduce((t, c)=> [c.item=[], t['' + c.id] = c, t][2], {});

let result =  menuArray.reduce((t, c)=>{
    if(menuDict[c.pid]) {
        menuDict[c.pid].item.push(c);
    } else {
        t.push(c)
    }
    return t 
}, [])

console.log(result);
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-1e45fd5-4cf18.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-1e45fd5-4cf18.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?