簡體   English   中英

插入一個新的 object 到陣列 Ramda

[英]Insert a new object to array Ramda

Ramda 有插入 function 但就我而言,我不知道如何鑽取 object 並將新的 object 插入到數組中。 還有一個新的 object 應該在數組的最后一個索引上,我們可以通過stuff["31"].length得到它。 我的嘗試太可悲了,所以我決定不展示它們:/

數據 model:

const stuff = {
  "31": [
    {
      "id": "11",
      "title": "ramda heeeelp"
    },
    {
      "id": "12",
      "title": "ramda 123"
    },
    //HERE I WANT TO INSERT A NEW OBJECT - {id: "13", title: "new title"}
  ],
  "33": [
    {
      "id": "3",
      "title": "..."
    }
  ],
  "4321": [
    {
      "id": "1",
      "title": "hello world"
    }
  ]
}

這是一個簡單的鏡頭使用, append添加到最后。

這是我的做法:

 const addObjToGroup = (groupId, newObj, data) => over (lensProp (groupId), append (newObj), data) const stuff = {"31": [{"id": "11", "title": "ramda heeeelp"}, {"id": "12", "title": "ramda 123"}], "33": [{"id": "3", "title": "..."}], "4321": [{"id": "1", "title": "hello world"}]} console.log ( addObjToGroup ('31', {id: "13", title: "new title"}, stuff) )
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> <script>const {over, lensProp, append} = R </script>

您還可以使用 Evolution to append 將該項目添加到groupId中的數組中:

 const { evolve, append } = R const addObjToGroup = (groupId, newObj) => evolve({ [groupId]: append(newObj) }) const stuff = {"31": [{"id": "11", "title": "ramda heeeelp"}, {"id": "12", "title": "ramda 123"}], "33": [{"id": "3", "title": "..."}], "4321": [{"id": "1", "title": "hello world"}]} const result = addObjToGroup ('31', {id: "13", title: "new title"})(stuff) console.log (result)
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

R.useWith在這里也有幫助!

 const appendTo = R.useWith(R.over, [ R.lensProp, R.append, R.identity ]); // --- const stuff = { "31": [ { "id": "11", "title": "ramda heeeelp" }, { "id": "12", "title": "ramda 123" }, //HERE I WANT TO INSERT A NEW OBJECT - {id: "13", title: "new title"} ], "33": [ { "id": "3", "title": "..." } ], "4321": [ { "id": "1", "title": "hello world" } ] } console.log( appendTo('31', 'HELLO WORLD', stuff), );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM