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:
__proxy and bringing its content upstate and bringing its content upI'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!
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With