I have an object of a state with some properties for example
function (location){ obj = { kids : { eyal : 21, noam :15 } pets : { dog : 5, cat :2 } } }
now I want to change eyal value
location = "kids.eyal"
if im doing
setobj((prevobj) => { ...prevobj, [location] : 22 })
it create new parameter in obj Kids.eyal = 22 instead of changing eyal in kids to 22 how can I fix it?
I think you want something like this:
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}))
Logic.
.Working Fiddle
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);
You can't use obj.property format inside [] brackets. You'll have to send the both properties separately. Something like
location = ["kids","eyal"]
and then use it there as:
setobj((prevobj) => { ...prevobj, [location[0]][location[1]] : 22 })
Hope it resolves the issue