简体   繁体   中英

Ramda - Convert array of objects into object

Looked around but couldn't find an answer to this.

Is there a more declarative way of doing this with ramda ?

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

Basically, I am converting an array that looks like this:

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

Into a single object that looks like this:

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

Map the the array into an array of [name, value] pairs, and then convert it to an object using 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>

With vanilla JS you can create the array of pairs (entries) by mapping the array, using destructuring, and then converting to object using 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM