Asking
Asking

Reputation: 4192

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?

Upvotes: 0

Views: 39

Answers (1)

hackape
hackape

Reputation: 19957

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
  }, {})
}

Upvotes: 1

Related Questions