通过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
,[ C0])。
Update:添加目标,如果键(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; }
在普通的Java语言中,<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
效果很好。
Array#splice
Array#splice
除非您需要以编程方式执行此操作,否则只需使用Javascript Array方法就可以移动对象。
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" }] };
stuff['33'].splice(1, 0, ...stuff['31'].splice(0, 1));
console.log(stuff);