Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda