Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
Duplicated entries when recursively creating new objects and storing their references

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda