Ramda - 将对象数组转换为对象

Ramda - Convert array of objects into object

环顾四周,但找不到答案。

ramda 是否有更明确的方式来做到这一点?

R.reduce((acc, val) => { 
  acc[val.name] = val.value
  return acc
}, {}, fields)

基本上,我正在转换一个如下所示的数组:

[
   { name: "firstName", value: "John" }, 
   { name: "lastName", value: "Doe" }
]

变成一个看起来像这样的对象:

{ firstName: "John", lastName: "Doe" }

将数组映射为 [name, value] 对数组,然后使用 R.fromPairs:

将其转换为对象

const { pipe, fromPairs, map, props } = R

const fn = pipe(map(props(['name', 'value'])), fromPairs)

const arr = [{ name: "firstName", value: "John" }, {name: "lastName", value: "Doe" }]

const result = fn(arr)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

使用普通 JS,您可以通过映射数组、使用解构然后使用 Object.fromEntries() 转换为对象来创建对(条目)数组:

const fn = arr => Object.fromEntries(arr.map(({ name, value }) => [name, value]))

const arr = [{ name: "firstName", value: "John" }, {name: "lastName", value: "Doe" }]

const result = fn(arr)

console.log(result)