将新对象插入数组Ramda

问题描述 投票:1回答:2

Ramda具有insert function。但是在我的情况下,我不知道如何钻取对象并将新对象插入数组。另外,新对象应位于数组的最后一个索引上,我们可以通过stuff["31"].length来获取它。我的尝试太可悲了,所以我决定不展示给他们:/

数据模型:

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"
    }
  ]
}
javascript object functional-programming ramda.js
2个回答
2
投票

这是镜头的简单用法,将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>

0
投票

您还可以使用Evolution将项目附加到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>
© www.soinside.com 2019 - 2024. All rights reserved.