I am trying to add a new object using the map, but the new object is not inserted, i think there is an issue with my logic,
What I am trying to is I have some results data, I am trying to structure it, the English 1st part will be an object and English 2nd part will be another object, these 2 objects will be inside children, like the example
[
{
title: "English",
children: [
0:{
title: "1ST",
children: [
{
title: "CQ",
dataIndex: "CQ",
},
{
title: "MCQ",
dataIndex: "MCQ",
},
],
},
1:{
title: "2ND",
children: [
{
title: "CQ",
dataIndex: "CQ",
},
{
title: "MCQ",
dataIndex: "MCQ",
},
],
}
]
Here is my code, the English 2nd part is not inserting
const results = [
{ Field: "english_1st_CQ" },
{ Field: "english_1st_MCQ" },
{ Field: "english_2nd_CQ" },
{ Field: "english_2nd_MCQ" },
];
const structureData = (results) => {
let arr = [];
results.map((value) => {
if (value.Field.includes("_")) {
const [subjectName, subjectPart, suffix] = value.Field.split("_");
const isSubjectExist = arr.find((el) => el.title == subjectName);
if (isSubjectExist !== undefined) {
isSubjectExist.children.map((element, i) => {
if (element.title == subjectPart) {
element = {
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
};
} else {
element.children["2"] = {
title: suffix,
dataIndex: suffix,
};
}
});
} else {
const subject = {
title: subjectName,
children: [
{
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
},
],
};
arr.push(subject);
}
}
});
return arr;
};
console.log(structureData(results));
The issue is here:
if (element.title == subjectPart) {
element = {
title: subjectPart,
children: [
{
title: suffix,
dataIndex: suffix,
},
],
};
CodePudding user response:
I think that using a functional approach helps to better keep track of and reason about what is happening during the iterations because it keeps things DRY:
function resolveNode (arr, title) {
const node = arr.find(node => node.title === title) ?? {title, children: []};
if (!arr.includes(node)) arr.push(node);
return node;
}
function parse (input) {
const result = [];
for (const {Field} of input) {
const [subject, part, suffix] = Field.split('_');
const s = resolveNode(result, subject);
const p = resolveNode(s.children, part);
// Don't create duplicates:
if (!p.children.find(node => node.title === suffix)) {
p.children.push({title: suffix, dataIndex: suffix});
}
}
return result;
}
const input = [
{ Field: "english_1st_CQ" },
{ Field: "english_1st_MCQ" },
{ Field: "english_2nd_CQ" },
{ Field: "english_2nd_MCQ" },
];
const result = parse(input);
const formattedJson = JSON.stringify(result, null, 2);
console.log(formattedJson);