Ramda 找到两个不同的嵌套键值

Ramda find two different nested key values

我在这个 Ramda 中是新手,可以在同一级别的对象中获取两个不同的键值吗?

我在下面添加了相同的代码:

这里list对象有users和employee关键字,我尝试实现同时获取users和employee详情

const R = require('ramda');

var list = [
  {"doc":{"Title":"test1","Relations":{"users":[{"name": "user1"}]}}},
  {"doc":{"Title":"test2","Relations":{"employee":[{"name": "user2"}]}}}
];

var getDetails=  R.map(
  R.pipe(
    R.prop('doc'),
    R.pipe(R.path(['Relations', 'users']))
  )
)

getDetails(list);

在我的代码中,我只使用了用户密钥。可以获得两个密钥(用户和员工)。

当前输出:

[[{"name": "user1"}], undefined]

期望输出:

[[{"name": "user1"}], [{"name": "user2"}]]

您可以使用 ifElseisNil 函数:

var getDetails=  R.map(
  R.pipe(
    R.prop("doc"),
    R.pipe(
      R.ifElse(
        R.pipe(R.path(["Relations", "users"]), R.isNil),
        R.path(["Relations", "employee"]),
        R.path(["Relations", "users"])
      )
    )
  )
)

你离现有的解决方案不远了。

其他一些可以提供帮助的函数是:

  • R.pick - 这会将对象转换为仅包含您提供的键(例如 usersemployee)。
  • R.values - Ramda 的功能相当于 Object.prototype.values.
  • R.chain - 这允许您映射列表,然后展平生成的嵌套列表。

const list = [
  {"doc":{"Title":"test1","Relations":{"users":[{"name": "user1"}]}}},
  {"doc":{"Title":"test2","Relations":{"employee":[{"name": "user2"}]}}}
]

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>