通过move 移动数组中的项目非常简单,但不幸的是,它并不像往常一样适合我。
例如,我需要将索引为 0 的对象从组 #31 移动到 #33,并将目标数组中对象的新索引设置为 1。
source_group_id
= 31source_object_index
= 0destination_group_id
= 33destination_object_index
= 1
数据对象模型:
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"
}
]
}
有人知道怎么解决吗?
最佳答案
您可以使用镜头来更改子对象,但您首先需要获取该项目。
首先使用 R.view
和 R.lensPath
来获取项目。然后使用 R.over
和 R.lenseProp
从源键和索引处的子对象中删除项目 (sk
, si
),然后将其插入目标键和索引(tk
, ti
)。
更新:添加一个目标,如果键(tk
)不存在,使用R.unless
检查R.has
用于tk
的存在,如果它不添加一个带有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>
关于javascript - 将对象从数组 A 移动到数组 B. Ramda.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121090/