Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda