Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda