[英]Insert a new object to array Ramda
Ramda has insert function . Ramda 有插入 function 。 But in my case I dunno how to drill through object and insert a new object to array.
但就我而言,我不知道如何钻取 object 并将新的 object 插入到数组中。 Also a new object should be on the last index of array, we can get it via
stuff["31"].length
.还有一个新的 object 应该在数组的最后一个索引上,我们可以通过
stuff["31"].length
得到它。 My attempts were too pathetic so I decided not to show them:/我的尝试太可悲了,所以我决定不展示它们:/
Data model:数据 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"
}
]
}
This is a straightforward use of lenses, with append
to add to the end.这是一个简单的镜头使用,
append
添加到最后。
Here is how I would do it:这是我的做法:
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>
You can also use evolve to append the item to the array in the groupId
:您还可以使用 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>
also R.useWith
helps here! 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.