Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!