Arthur
Arthur

Reputation: 3516

Insert a new object to array Ramda

Ramda has insert function. But in my case I dunno how to drill through object and insert a new object to array. Also a new object should be on the last index of array, we can get it via stuff["31"].length. My attempts were too pathetic so I decided not to show them :/

Data 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"
    }
  ]
}

Upvotes: 1

Views: 5049

Answers (3)

Hitmands
Hitmands

Reputation: 14199

also R.useWith helps here!

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>

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193047

You can also use evolve to append the item to the array in the 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>

Upvotes: 1

Scott Sauyet
Scott Sauyet

Reputation: 50807

This is a straightforward use of lenses, with append to add to the end.

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>

Upvotes: 2

Related Questions