My array consists of classes:
const transferClasses = [
{
id: "c5d91430-aaab-ed11-8daf-85953743f5cc",
name: "Class1",
isTransfer: false,
children: [],
},
{
id: "775cb75d-aaab-ed11-8daf-85953743f5cc",
name: "Class2",
isTransfer: false,
children: [
{
id: "89134f56-3ef6-ed11-8daf-85953743f5cc",
name: "Class2-1",
isTransfer: false,
children: [],
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f4cc",
name: "Class2-2",
isTransfer: false,
children: [
{
id: "89134f56-3ef6-ed11-8daf-85953743f4de",
name: "Class2-2-1",
isTransfer: false,
children: [],
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f1ce",
name: "Class2-2-2",
isTransfer: false,
children: [],
},
],
},
],
},
];
I am looking to convert this nested array into a flat list. For example:
const flatList = [
{
id: "c5d91430-aaab-ed11-8daf-85953743f5cc",
name: "Class1",
isTransfer: false,
childrenId: null,
parentId: null,
},
{
id: "775cb75d-aaab-ed11-8daf-85953743f5cc",
name: "Class2",
isTransfer: false,
childrenId: [
"89134f56-3ef6-ed11-8daf-85953743f5cc",
"89134f56-3ef6-ed11-8daf-85953743f4cc",
],
parentId: null,
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f5cc",
name: "Class2-1",
isTransfer: false,
childrenId: [],
parentId: ["775cb75d-aaab-ed11-8daf-85953743f5cc"],
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f5cc",
name: "Class2-2",
isTransfer: false,
childrenId: [
"89134f56-3ef6-ed11-8daf-85953743f4de",
"89134f56-3ef6-ed11-8daf-85953743f1ce",
],
parentId: ["775cb75d-aaab-ed11-8daf-85953743f5cc"],
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f4de",
name: "Class2-2-1",
isTransfer: false,
childrenId: [],
parentId: ["89134f56-3ef6-ed11-8daf-85953743f5cc"],
},
{
id: "89134f56-3ef6-ed11-8daf-85953743f1ce",
name: "Class2-2-2",
isTransfer: false,
childrenId: [],
parentId: ["89134f56-3ef6-ed11-8daf-85953743f5cc"],
},
];
Each element should have the ids of its parents and children listed.
Below is my function code. While I've handled the children, I'm stuck on how to include the parents.
export const getFlatList = (classes) => {
return classes.map((cl) => {
const getChildIds = (classes) => {
return classes.map((cl) => {
if (cl.children.length > 0) {
getChildIds(cl.children);
} else {
return cl.id;
}
return cl.id;
});
};
return {
id: cl.id,
name: cl.name,
isTransfer: cl.isTransfer,
children: getChildIds(cl.children),
parentId: ?? // :(
};
});
};