Node Ramda + find the object based on value

大憨熊 提交于 2019-12-08 11:56:20

问题


Possible to get object based on the value?

In below sample json, the key name have type, so based on type value need to fetch the results.

For example if type='user' then fetch the result only for users object not for employee object.

Here I am struggling have both keys(users and employee), Could you please suggest to how to approach

var list =[
  {"doc":{"type":"user","Title":"test1","Relations":{"users":[{"name": "user1"},{"name": "user2"},{"name": "user3"}],"employee":[{"emp": "user2"}]}}},
  {"doc":{"type":"employee","Title":"test2","Relations":{"users":[{"name": "user1"}],"employee":[{"name": "emp1"},{"name": "emp2"},{"name": "emp3"}]}}}
];

const getDetails = R.chain(R.pipe(
  R.path(['doc', 'Relations']),
  R.pick(['users', 'employee']),
  R.values
))

const result = getDetails(list)

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

Current Output:

[[{"name": "user1"}, {"name": "user2"}, {"name": "user3"}], [{"emp": "user2"}], [{"name": "user1"}], [{"name": "emp1"}, {"name": "emp2"}, {"name": "emp3"}]]

Expecting output:

[[{"name": "user1"}, {"name": "user2"}, {"name": "user3"}], [{"name": "emp1"}, {"name": "emp2"}, {"name": "emp3"}]]

回答1:


You can make use of R.cond to branch logic based on a set of predicates, like whether type is user or employee in your example.

With this approach you will need to switch your R.chain to R.map to match your expected list, unless you want the extra flattening of the arrays.

const list = [
  {"doc":{"type":"user","Title":"test1","Relations":{"users":[{"name": "user1"},{"name": "user2"},{"name": "user3"}],"employee":[{"emp": "user2"}]}}},
  {"doc":{"type":"employee","Title":"test2","Relations":{"users":[{"name": "user1"}],"employee":[{"name": "emp1"},{"name": "emp2"},{"name": "emp3"}]}}}
]

const getDetails = R.map(R.pipe(
  R.prop('doc'),
  R.cond([
    [R.propEq('type', 'user'), R.path(['Relations', 'users'])],
    [R.propEq('type', 'employee'), R.path(['Relations', 'employee'])]
  ])
))

const expected = [[{"name": "user1"}, {"name": "user2"}, {"name": "user3"}], [{"name": "emp1"}, {"name": "emp2"}, {"name": "emp3"}]]

console.log(R.equals(expected, getDetails(list)))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


来源:https://stackoverflow.com/questions/51170414/node-ramda-find-the-object-based-on-value

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