简体   繁体   中英

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.

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.

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