Skip to main content

How to remove keys and lift props up?

Given the following object:

{
  __proxy: {
    state: {
      count: 0
      items: {
        __proxy: {
          state: {
            amount: 0
          }
        }
      }
    }
  }
}

I'd like to convert it to:

{
  count: 0,
  items: {
    amount: 0
  }
}

So, as you can see, I'm doing a few things:

  1. Removing __proxy and bringing its content up
  2. Removing state and bringing its content up
  3. All of the above recursively.

I've tried something like the snippet below:

const removeKeys = (obj, keys) => obj !== Object(obj)
      ? obj
      : Array.isArray(obj)
      ? obj.map((item) => removeKeys(item, keys))
      : Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));

removeKeys(myObj, ['__proxy', 'state'])

However, it completely removes __proxy and/or state - and I want to preserve their content.

That said, do you know any existing solution for that? A NPM library, perhaps? Or a lodash function?

Thanks!

Via Active questions tagged javascript - Stack Overflow https://ift.tt/8u6HOro

Comments