considere este JSON como un producto y podría tener infinitos productos secundarios.
Necesito una función que recorra la propiedad de productos secundarios y agregue un elemento secundario en el lugar correcto:
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; };para un mejor entendimiento:
childTree es la matriz principal/primer childProduct del producto.
nestedChildIndex es la matriz de índices que determina qué tan profundo debo profundizar dentro de childProducts , es algo como esto: ['0', '0'] dice que en los productos secundarios debo ir al index 0 de eso y luego dentro de childProducts of index 0 , debería ir al índice 0 (espero que no te hayas confundido)
y updatedChild es el nuevo objeto secundario que necesito agregar. (Lo obtengo de un formulario pero el formato es el mismo que otros)
Entonces, ¿cómo puedo alterar este bucle para lograr mi objetivo?
Manejo el problema alterando el código así:
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}; };Te has perdido la reasignación del newChild con bucles internos
for (let i = 0; i < nestedChildIndex.length; i++) { newChild = newChild.childProducts[nestedChildIndex[i]].listOfNewCustomProduct[nestedChildIndex[i]]; }