Tengo un objeto de un estado con algunas propiedades por ejemplo
function (location){ obj = { kids : { eyal : 21, noam :15 } pets : { dog : 5, cat :2 } } }
ahora quiero cambiar el valor de eyal
location = "kids.eyal"
si estoy haciendo
setobj((prevobj) => { ...prevobj, [location] : 22 })
crea un nuevo parámetro en obj Kids.eyal = 22 en lugar de cambiar eyal en kids a 22, ¿cómo puedo solucionarlo?
Creo que quieres algo como esto:
oldObj = { kids : { eyal : 21, noam :15 } } function updateOneKidAge(obj,theKid) { const [kidName, newAge] = Object.entries(theKid)[0] return { kids : {...obj.kids, [kidName]: newAge}}; } console.log(updateOneKidAge(oldObj, {eyal: 22}))Lógica.
.violín de trabajo
const obj = { kids : { eyal : 21, noam :15 }, pets : { dog : 5, cat :2 } }; const targetLocation = "kids.eyal"; const pathArray = targetLocation.split('.'); const lastNode = pathArray[pathArray.length - 1]; let node = obj; pathArray.forEach((path, index) => node = index === pathArray.length - 1 ? node : node [path]); node[lastNode] = 22; console.log(obj);No puede usar el formato obj.property dentro de [] corchetes. Tendrás que enviar las dos propiedades por separado. Algo como
location = ["kids","eyal"]y luego usarlo allí como:
setobj((prevobj) => { ...prevobj, [location[0]][location[1]] : 22 })Espero que resuelva el problema.