Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove keys and lift props up?

Tags:

javascript

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? An NPM library, perhaps? Or a lodash function?

Note: Since I'm using TypeScript, a typed solution would be preferred, but raw js works well either.

Thanks!

like image 331
Guilherme Oderdenge Avatar asked Oct 22 '25 04:10

Guilherme Oderdenge


1 Answers

You could destructure the unwanted properties and move the content a level up.

const
    convert = ({ __proxy, state, ...object }) => __proxy || state
        ? convert({ ...(__proxy || {}), ...(state || {}), ...object })
        : Object.fromEntries(Object
            .entries(object)
            .map(([k, v]) => [k, v && typeof v === 'object' ? convert(v) : v])
    )
    data = { __proxy: { state: { count: 0, items: { __proxy: { state: { amount: 0 } } } } } },
    result = convert(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 149
Nina Scholz Avatar answered Oct 23 '25 18:10

Nina Scholz