1

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" }
1
  • While OriDrori's Ramda answer may be slightly more readable, note that this is pretty clear with vanilla JS: const convert = (xs) => Object .fromEntries (xs .map (({name, value}) => [name, value])) Commented Nov 6, 2020 at 21:42

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.