ABC
ABC

Reputation: 1477

How to sort an array of objects based on nested key using Ramda?

I start off with an object like this:

const myObj = {
  key1: {a: 123, b: 'some field1'},
  key2: {a: 1, b: 'some field2'},
  key3: {a: 123123, b: 'some field3'}
}

I convert it to an array using R.toPairs, resulting in:

[
  ["key1", {"a": 123, "b": "some field1"}], 
  ["key2", {"a": 1, "b": "some field2"}], 
  ["key3", {"a": 123123, "b": "some field3"}]
]

Not sure now how to sort this array on the deeper key a. I hear Ramda's lenses could help but not sure how. I'm also open to non-lens approaches too.

Upvotes: 4

Views: 4117

Answers (1)

georg
georg

Reputation: 214959

A straightforward way is to compose two props:

R.sortBy(
    R.compose(
        R.prop('a'), R.prop(1)
    )
)
(R.toPairs(myObj))

See this recipe if you need more nesting.

Upvotes: 12

Related Questions