It's pretty simple to move item in array via move, but unfortunately it's not suitable in my case as usual.
For example I need to move object with index 0 from group #31 to #33 and set the new index for object in the destination array to 1.
source_group_id
= 31source_object_index
= 0destination_group_id
= 33destination_object_index
= 1Data object model:
const stuff = {
"31": [
{------------------------------|
"id": "11", |============|
"title": "Just move me pls" | ||
},-----------------------------| ||
{ ||
"id": "12", ||
"title": "Ramda 123" ||
}, ||
], ||
"33": [ ||
{ ||
"id": "3", ||
"title": "Ramda jedi" ||
} ||
◀==========================================|
],
"4321": [
{
"id": "1",
"title": "Hello Ramda"
}
]
}
Does anyone know how to solve this?
You can use lenses to change the sub-objects, but you'll first need to get the item.
Start by using R.view
with R.lensPath
to get the item. Then use R.over
with R.lenseProp
to remove the item from sub-object at the source key and index (sk
, si
), and then to insert it to the target key and index (tk
, ti
).
Update: to add a target, if the key (tk
) doesn't exist, use R.unless
to check with R.has
for the existence of tk
, and if it doesn't add an empty array with R.assoc
.
const { curry, view, lensPath, pipe, over, lensProp, remove, unless, has, assoc, insert } = R;
const fn = curry(({ key: sk, idx: si }, { key: tk, idx: ti }, obj) => {
const item = view(lensPath([sk, si]), obj); // get the item
return pipe(
over(lensProp(sk), remove(si, 1)), // remove the item from the source
unless(has(tk), assoc(tk, [])), // add target if it's missing
over(lensProp(tk), insert(ti, item)), // move to the target
)(obj);
});
const stuff = { 31: [{ id: "11", title: "just move me pls" }, { id: "12", title: "ramda 123" }], 33: [{ id: "3", title: "..." }], 4321: [{ id: "1", title: "hello Ramda" }] };
console.log(fn({ key: '31', idx: 0 }, { key: 33, idx: 1 }, stuff));
console.log(fn({ key: '31', idx: 0 }, { key: 555, idx: 1 }, stuff));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments