Ramda: convert key value array to object

Viewed 1502

I'm using Ramda to sort a normalized model object by key. Firstly I convert to key|value pairs (equivalent of Object.entries), and sort by the first value using R.head (the key value when in pairs)

I want to convert the resulting sorted array of pairs to an array of objects - in the example code I'm using ES6+ map and array destructuring

const data = {
  2: {name: 'two'},
  1: {name: 'one'}
}

const sortByKey = R.compose(R.sortBy(R.head), R.toPairs);
const sortedPairs = sortByKey(data)
console.log(sortedPairs)
// [["1",{"name":"one"}],["2",{"name":"two"}]]

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})
console.log(objs)
// [{"1":{"name":"one"}},{"2":{"name":"two"}}]

The part I can't find a Ramda function for is

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})
2 Answers

You can use R.map with applied R.objOf to convert an array of pairs ([key, value]) to an array objects

const { compose, map, apply, objOf, sortBy, head, toPairs } = R

const sortByKey = compose(sortBy(head), toPairs)
const arrayFromPairs = map(apply(objOf))

const data = {
  2: {name: 'two'},
  1: {name: 'one'}
}

const result = arrayFromPairs(sortByKey(data))

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

You can use compose(fromPairs, of) to create an object from a single pair.

const fromPair = compose(fromPairs, of);
fromPair(["a", 1]);
//=> {"a": 1}

const { compose, fromPairs, head, map, of, sortBy, toPairs } = R;

const sortByKey = compose(sortBy(head), toPairs);
const fromPair = compose(fromPairs, of);
const arrayFromPairs = map(fromPair);

const data = {
  2: {name: 'two'},
  1: {name: 'one'},
};

const sortedPairs = sortByKey(data);
const objs = arrayFromPairs(sortedPairs);
console.log(objs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>

Related