Find an object by id in array Ramda

眉间皱痕 提交于 2019-12-11 09:10:58

问题


For example I have something like:

const stuff = {
  "31": [
    {
      "id": "11",
      "title": "ramda heeeelp"
    },
    {
      "id": "12",
      "title": "ramda 123"
    }
  ],
  "33": [
    {
      "id": "3",
      "title": "..."
    }
  ],
  "4321": [
    {
      "id": "1",
      "title": "hello world"
    }
  ]
}

I need to find object with id 11. How I did:

map(key => find(propEq('id', 11))(stuff[key]), keys(stuff)) 

However it returns [{..object with id 11..}, undefined, undefined] due to map. Ok, we could check if object isn't undefined, but it isn't clear as I want.


回答1:


Get the values of the object, flatten the array of arrays, and use find and propEq to get the object:

const { pipe, values, flatten, find, propEq } = R

const findById = id => pipe(
  values,
  flatten,
  find(propEq({ id }))
)

const data = {"31":[{"id":"11","title":"ramda heeeelp"},{"id":"12","title":"ramda 123"}],"33":[{"id":"3","title":"..."}],"4321":[{"id":"1","title":"hello world"}]}

const result = findById('11')(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>


来源:https://stackoverflow.com/questions/58683743/find-an-object-by-id-in-array-ramda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!