javascript - 将对象从数组 A 移动到数组 B. Ramda.js

标签 javascript arrays object functional-programming ramda.js

通过move 移动数组中的项目非常简单,但不幸的是,它并不像往常一样适合我。

例如,我需要将索引为 0 的对象从组 #31 移动到 #33,并将目标数组中对象的新索引设置为 1。

  • source_group_id = 31
  • source_object_index = 0
  • destination_group_id = 33
  • destination_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.viewR.lensPath 来获取项目。然后使用 R.overR.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/

相关文章:

javascript - 加载图片到div,涉及到PHP和jQuery

javascript - 从 html select 无按钮提交,但使用 href 而不是 value?

javascript - CouchDB 设计文档中的多个 validate_doc_update 函数。有什么好的做法吗?

检查 C 中的数组是否对称

c++ - openGL 和 vector

javascript - 在数组中查找对象值 Vue Javascript Vuex?

javascript - 如何根据下拉结果让 knockout 网格显示标题和数据

java - void方法中使用的void方法的组成? ( java )

C#对象和内存管理

javascript - 用 Javascript 中的对象填充数组