0

How do I create a utility function that creates a new object by recursively 'cloning' an object and applying a function to its keys/values/index? (Much like the solution here, but for deep nested objects: map function for objects (instead of arrays))


const light = {
  a: 'light-a',
  b: {
    b1: 'light-b1',
    b2: 'light-b2'
  }
}

const dark = {
  a: 'dark-a',
  b: {
    b1: 'dark-b1',
    b2: 'dark-b2'
  }
}

// const deepMapObjectFunction = () => ...

const lightAndDark = deepMapObjectFunction(light, (key, value index) => ({
  light: value,
  dark: dark[key],
}))

console.log(lightAndDark)
/*
{
  a: { light: 'light-a', dark: 'dark-a'},
  b: {
    b1: {
      light: 'light-b1',
      dark: 'dark-b1',
    },
    b2: {
      light: 'light-b2',
      dark: 'dark-b2',
    },
  }
}
*/
Stephen Koo
  • 447
  • 1
  • 5
  • 10
  • Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – pintxo Aug 19 '20 at 12:53
  • How do you suppose `dark[key]` will work, since `key` will be a property of your nested objects, doing `dark[key]` will give undefined once traversing the nested objects – Nick Parsons Aug 19 '20 at 12:57
  • @charlietfl That question doesn't seem to have answers which perform a deep-map of the inner objects though, or am I missing something? – Nick Parsons Aug 19 '20 at 13:08
  • @NickParsons I see numerous different recursive functions in various answers such as https://stackoverflow.com/questions/38416020/deep-copy-in-es6-using-the-spread-syntax or https://stackoverflow.com/a/63371541/1175966 or https://stackoverflow.com/a/53211934/1175966 If you have a better canonical post for deep copying feel free to add it – charlietfl Aug 19 '20 at 13:19
  • @charlietfl yeah, I didn't see [this](https://stackoverflow.com/a/63371541/5648954) answer, since is towards the bottom, but it seems to be just doing a deep-clone and isn't applying a transformation/mapping function to the object, but I guess OP might be able to work out how to apply a mapping function to transform the object based on the logic presented in that answer... – Nick Parsons Aug 19 '20 at 13:27

0 Answers0