I have a interface Article which contains a field with an array of Article. I now have a similar class which should contain the same data and references. My goal is now to create an object for each Article and their references.
interface Article{
title:string;
sections:Array<Article>;
}
class ArticleClass{
constructor(article:Article) {
buildRefs(this, article);
}
sections:Array<ArticleClass>;
buildRefs(parent: ArticleClass, data: Article): void {
data.sections.forEach((s) => {
const nextParent = new ArticleClass(s);
this.buildRefs(nextParent, s);
parent.sections.push(nextParent);
});
}
}
// Example
const articleData = {
title:"Main Article",
sections:[
{title: "1.1", sections:[]},
{title: "1.2", sections:[{title: "1.2.1", sections:[]},{title: "1.2.2",
sections:[]},]},
{title: "1.3", sections:[]},,
];
const mainArticle = new ArticleClass(articleData);
}
In the constructor I recursively create all the objects and save the references of the current level in the sections array.
However when I run this, for some reason, the articles 1.2.1 and 1.2.2 are duplicated. Everything is is the right place though, only those two are duplicated.