Given that I have an object like this
const data = {
_id: "62bac5af6b6581786cb192e4",
name: "components",
subCategories: [
{
_id: "62bac9a24bd73045dcb563d7",
name: "RAM",
subCategories: [
{
_id: "62bc21152fde7012505b93a4",
name: "SRAM",
subCategories: [],
},
{
_id: "62bc220ff4b1a343a4d2ec9d",
name: "DRAM",
subCategories: [],
},
],
},
{
_id: "62baca1a1ffdc142085bca80",
name: "Motherboard",
subCategories: [
{
_id: "62baca1a1ffdc142085bca82",
name: "AT",
subCategories: [],
},
{
_id: "62baca1a1ffdc142085bca83",
name: "ATX",
subCategories: [],
},
],
},
],
};
I would like to create a brand new object that would look like this
const data = {
value: "62bac5af6b6581786cb192e4",
title: "components",
children: [
{
value: "62bac9a24bd73045dcb563d7",
title: "RAM",
children: [
{
value: "62bc21152fde7012505b93a4",
title: "SRAM",
children: [],
},
{
value: "62bc220ff4b1a343a4d2ec9d",
title: "DRAM",
children: [],
},
],
},
{
value: "62baca1a1ffdc142085bca80",
title: "Motherboard",
children: [
{
value: "62baca1a1ffdc142085bca82",
title: "AT",
children: [],
},
{
value: "62baca1a1ffdc142085bca83",
title: "ATX",
children: [],
},
],
},
],
};
So my logic was to loop through all the subcategories and insert it as a child. Following is what I have tried
const iterate = (data) => {
let result = {
title: data.name,
value: data._id,
children: [],
};
function loop(data, result) {
for (const category of data) {
let subItem = {
title: category.name,
value: category._id,
children: [],
};
result.children.push(subItem);
if (category.subCategories) {
loop(category.subCategories, result);
}
}
}
loop(data.subCategories, result);
return result;
};
const res = iterate(data);
console.log(res);
I end up getting something like this
{
"title": "components",
"value": "62bac5af6b6581786cb192e4",
"children": [
{
"title": "RAM",
"value": "62bac9a24bd73045dcb563d7",
"children": []
},
{
"title": "SRAM",
"value": "62bc21152fde7012505b93a4",
"children": []
},
{
"title": "DRAM",
"value": "62bc220ff4b1a343a4d2ec9d",
"children": []
},
{
"title": "Motherboard",
"value": "62baca1a1ffdc142085bca80",
"children": []
},
{
"title": "AT",
"value": "62baca1a1ffdc142085bca82",
"children": []
},
{
"title": "ATX",
"value": "62baca1a1ffdc142085bca83",
"children": []
}
]
}
Kinda stuck here, really appreciate all the help given, thank you.
CodePudding user response:
You can try this:
const transform = (data) => {
const result = {
title: data.name,
value: data._id,
children: data.subCategories.map(transform),
};
return result;
}
const newData = transform(data);