I am having an array of objects that looks like this
const input = [
{
group: {
id: "group1",
groupName: "Group1"
},
categories: [
{
id: "category11",
categoryName: "Category 11",
subCategories: []
}
]
},
{
group: {
id: "group2",
groupName: "Group 2"
},
categories: [
{
id: "category21",
categoryName: "Category 21",
subCategories: []
},
{
id: "category22",
categoryName: "Category 22",
subCategories: [
{
id: "category221",
categoryName: "Category 221",
subCategories: []
}
]
}
]
}
];
I want this array to be translated into below array of objects, with objects containing key, name and categories
as its standard format to maintain the uniformity.
const output = [
{
key: "group1",
name: "Group1",
categories: [
{
key: "category11",
name: "Category 11",
categories: []
}
]
},
{
key: "group2",
name: "Group 2",
categories: [
{
key: "category21",
name: "Category 21",
categories: []
},
{
key: "category22",
name: "Category 22",
categories: [
{
key: "category221",
name: "Category 221",
categories: []
}
]
}
]
}
];
The first level of each object inside input
should be considered as root in the final output and rest of items should be nested recursively inside this first level.
The code that I tried
const output = arr.map((item) => {
return {
key: item.group.id,
name: item.group.groupName,
categories: [{ ...item }]
};
});
I was able to format the first level, but not the entire output. Can someone help me here?
4
Answers
You can use recursivity for that
You could take a recursive approach with some renaming.
A simple recursive function:
Try it:
You can do that pretty efficiently when you use a map object which maps old property names to new ones: