Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Change a value of a key by Variable string in nested object

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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}))
about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!