lodash通过具有对象数组的属性对对象数组进行排序

时间:2019-07-02 21:12:01

标签: ecmascript-6 lodash

我有一个对象。我可以使用lodash的_.orderBy()对项目进行排序。 但是,在一种情况下,我必须按subject进行排序,这是一个对象数组。 subject数组中的项目已经根据name进行了排序。

由于subject是对象的数组,因此我需要考虑用于排序的第一项。

[
  {
    "id": "1",
    "name": "peter",
    "subject": [
      {
        "id": "1",
        "name": "maths"
      },
      {
        "id": "2",
        "name": "social"
      }
    ]
  },
  {
    "id": "2",
    "name": "david",
    "subject": [
      {
        "id": "2",
        "name": "physics"
      },
      {
        "id": "3",
        "name": "science"
      }
    ]
  },
  {
    "id": "3",
    "name": "Justin",
    "subject": [
    ]
  }
]

3 个答案:

答案 0 :(得分:1)

您可以使用_.get()提取name中第一项的id(或subjects)。如果不存在任何项目,_.get()将返回undefined,可以将其替换为默认值。在这种情况下,我们不想使用空字符串作为默认值,因为顺序会改变。相反,我正在检查值是否为字符串,是否为小写,否则返回原样。

const arr = [{"id":"1","name":"peter","subject":[{"id":"1","name":"maths"},{"id":"2","name":"social"}]},{"id":"2","name":"david","subject":[{"id":"2","name":"physics"},{"id":"3","name":"science"}]},{"id":"3","name":"Justin","subject":[]}]

const result = _.orderBy(arr, o => {
  const name = _.get(o, 'subject[0].name')
  
  return _.isString(name) ? name.toLowerCase() : name
})

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

答案 1 :(得分:0)

_.sortBy与比较/排序函数参数一起使用。您的函数本身可以查看接收参数subject键(我想比较一下它的主题吗?)

答案 2 :(得分:0)

由于您也有用ES6标记的问题,因此这里是通过Array.sort的纯JS解决方案:

let arr = [ { "id": "1", "name": "peter", "subject": [ { "id": "1", "name": "maths" }, { "id": "2", "name": "social" } ] }, { "id": "2", "name": "david", "subject": [ { "id": "2", "name": "physics" }, { "id": "3", "name": "science" } ] }, { "id": "3", "name": "Justin", "subject": [] }, ] 

const result = arr.sort((a,b) => 
  a.subject.length && b.subject.length 
   ? a.subject[0].name.localeCompare(b.subject[0].name) 
   : a.subject.length ? -1 : 1)

console.log(result)