I'm building myself an admin dashboard in NextJS 13, and I have been struggling with converting arrays using ES6 functions.
For instance, I have the following array:
["","1","Mobile Phones"], //corresponding to ParentID, ID, Name
["1","2","Apple"],
["1","3","Samsung"],
["","4","Tablets"],
["4","5","Huawei"],
How can I convert it to the below object array like the below?
[
{
id: 1,
name: "Mobile Phones",
children: [
{
id: 2,
name: "Apple",
children: [],
},
{
id: 3,
name: "Samsung",
children: [],
},
],
},
{
id: 4,
name: "Tablets",
children: [
{
id: 5,
name: "Huawei",
children: [],
},
],
},
];
I have tried using array.map but I got the wrong result as shown below
[
{
id: 1,
name: "Mobile Phones",
children: [],
},
{
id: 2,
name: "Apple",
children: [],
},
{
id: 3,
name: "Samsung",
children: [],
},
{
id: 4,
name: "Tablets",
children: [],
},
{
id: 5,
name: "Huawei",
children: [],
},
];