0

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?

eyal
  • 23
  • 4
  • Does this answer your question? [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path) – pilchard Nov 28 '21 at 14:20

3 Answers3

0

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}))
skara9
  • 4,042
  • 1
  • 6
  • 21
  • It wont help because the object the need to be change is based on the parameter that the function get, and if there is two nested objects it wont work correctly – eyal Nov 29 '21 at 07:10
0

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);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

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