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

154
Vistas
traverse trough an object and add a new property/object?

consider this JSON as a product and it could have infinite child products.

I need a function that loop through child products property and add a child to the right place:

export const addChildProduct = (childTree, nestedChildIndex, updatedChild) => {
    let newChild = childTree;
    for (let i = 0; i < nestedChildIndex.length; i++) {
        newChild.childProducts[nestedChildIndex[i]].listOfNewCustomProduct[nestedChildIndex[i]];
    }
    newChild.childProducts === null
        ? (newChild.childProducts = Array.of(updatedChild))
        : newChild.childProducts.push(updatedChild);
    return newChild;
};

for better understanding:

childTree is the main/first childProduct array of the product.

nestedChildIndex is the array of indexes that determines how deep should I go inside childProducts, it's something like this: ['0', '0'] says that in the child products I should go to index 0 of that and then inside childProducts of index 0, I should go into index 0 (hope you didn't confuse)

and updatedChild is the new child object I need to add. (I get that from a form but format is the same as others)

so how can I alter this loop to achieve my goal?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I manage the issue by altering the code like so:

export const addChildProduct = (childTree, nestedChildIndex, updatedChild) => {
    let newChild = childTree;
    for (let i = 0; i < nestedChildIndex.length; i++) {
        newChild = newChild.childProducts[nestedChildIndex[i]].listOfNewCustomProduct[nestedChildIndex[i]];
    }
    newChild.childProducts === null
        ? (newChild.childProducts = Array.of(updatedChild))
        : newChild.childProducts.push(updatedChild);

    return {...childTree, childProducts: newChild};
};

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have missed reassigning the newChild with inner loops

 for (let i = 0; i < nestedChildIndex.length; i++) {
        newChild = newChild.childProducts[nestedChildIndex[i]].listOfNewCustomProduct[nestedChildIndex[i]];
    }
about 4 years ago · Juan Pablo Isaza Denunciar
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