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

110
Visualizações
Run a function recursivelly in Javascript

I created this function:

const demoD = (
  obj,
  toChange,
  newV,
) => {
  return Object.keys(obj).reduce((acc, key) => {

    if (typeof obj[key] === 'object') {
      demoD(obj[key], toChange, newV);
    }
    acc[key] = obj[key] === toChange ? newV : obj[key]
    return acc
  }, {})
}

const obj = {
  name: '',
  age: '687',
  demo: {
    test: ''
  }
}

console.log(demoD(obj, '', null))

The idea of this function is to change a value from the object with a new one, and it should run recursivelly.
I expect this result:

const obj = {
  name: null',
  age: '687',
  demo: {
    test: null'
  }
}

But i don't get this result, and the test still unchanged.
Question: How to fix and what is the issue?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you want to apply change to the original object in place:

const demoD = (
  obj,
  toChange,
  newV,
) => {
  return Object.keys(obj).reduce((acc, key) => {

    if (typeof obj[key] === 'object') {
      demoD(obj[key], toChange, newV);
    }
    acc[key] = obj[key] === toChange ? newV : obj[key]
    return acc
  }, obj) // 👈 send in obj here
}

If you don’t want to mutate your original object, then it should be:

const demoD = (
  obj,
  toChange,
  newV,
) => {
  return Object.keys(obj).reduce((acc, key) => {

    if (typeof obj[key] === 'object') {
      acc[key] = demoD(obj[key], toChange, newV)
    } else {
      acc[key] = obj[key] === toChange ? newV : obj[key]
    }
    return acc
  }, {})
}
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