0

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?

3
  • 1
    Your recursive call to demoD is not doing anything with the return value. Commented Sep 9, 2021 at 17:40
  • How to change the function? Commented Sep 9, 2021 at 17:42
  • change the recursive call to return demoD(obj[key], toChange, newV); Commented Sep 9, 2021 at 17:44

1 Answer 1

1

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
  }, {})
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.