object-traversal
object-traversal copied to clipboard
Mutate root object
Hello! Still using your lib a lot :)
I was wondering if you have any idea in how to mutate the root object without throwing weird javascript errors.
Lets imagine we have this format of nested objects, which could start as arrays or single objects at the root
{ $thing: 'Employee', $id: ['e1','e2'], companies: [{$id: ['c1','c2'], $op: 'link'}]}
Now imagine we want to split the $ids when they are arrays to have this output:
[
{
$thing: 'Employee
$id: 'e1'
companies: { $op: 'link' , $id: 'c1'} , { $op: 'link', $id: 'c2'}
},
{
$thing: 'Employee
$id: '21'
companies: { $op: 'link' , $id: 'c1'} , { $op: 'link', $id: 'c2'}
}
]
We could imagine something like this:
return produce(blocks, (draft) =>
traverse(draft, ({ value, key, parent }: TraversalCallbackContext) => {
if (isObject(val) && isArray(val.$id) {
parent[key] = value.$ids.map((id) => ({...value, $id: id})
}
}
);
This has obvious issues:
- Not working for the root (no parent)
- Is actually adding nested arrays in things that are already arrays (not a flatMap)
In general I realized it is cleaner to modify this objects from their parent, but then i need to create two different logics, one for the root, and then other for the rest.
Also being able to do transformation directly at the value level is convinient, because we can delete, update and add keys of that value easily
Do you have any idea in how could we do a wrapper around the traverse to manage this cases in a simple way, ensuring no JS object mutation errors and being able to avoid doing the particular cases for the root levels?