Home > Blockchain >  traverse trough an object and add a new property/object?
traverse trough an object and add a new property/object?

Time:11-22

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?

CodePudding user response:

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};
};

CodePudding user response:

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]];
    }
  • Related