Home > front end >  Change a value of a key by Variable string in nested object
Change a value of a key by Variable string in nested object

Time:11-29

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?

CodePudding user response:

Logic.

  • Split the location on .
  • Loop through the location array except for the last node.
  • Replace the last node object which is the required target with the required value.

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

CodePudding user response:

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

  • Related