admin管理员组

文章数量:1292244

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.

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.

Share asked Feb 27, 2016 at 16:00 ABCABC 1,4873 gold badges19 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

A straightforward way is to pose two props:

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

See this recipe if you need more nesting.

本文标签: javascriptHow to sort an array of objects based on nested key using RamdaStack Overflow