【问题标题】:Sort Object by children value using lodash使用 lodash 按子值对对象进行排序
【发布时间】:2020-02-20 20:36:33
【问题描述】:

我有以下对象:

const object = {
  "9c8vDTruRDPi937aHMMz":{
    name: "item1",
    createdAt: {
      seconds: 1582227276, 
      nanoseconds: 68000000
    }
  },
  "rAexYu2rAz0AEnD77x5p":{
    name: "item2",
    createdAt: {
      seconds: 1582227577,
      nanoseconds: 922000000
    }
  }
}

并希望根据 createdAt.seconds 对其进行排序并将其保留为对象。

例如,返回值将是(如果根据秒数和 Desc 排序):

const sortedByDateObject = {
  "rAexQu3rdm0AEnD77x5p":{
    name: "item2",
    createdAt: {
      seconds: 1582227577,
      nanoseconds: 922000000
    }
  },
  "9c8vDGryRSZi817aHMMz":{
    name: "item1",
    createdAt: {
      seconds: 1582227276, 
      nanoseconds: 68000000
    }
  }
}

知道如何使用 lodash 对数组进行排序,但不知道这种带有嵌套对象的复杂任务。

非常感谢任何帮助:)

【问题讨论】:

  • 没错,你应该使用一个对象数组[{key: value}, {key: value}],在这种情况下顺序是有保证的,我也不认为你可以在一个对象中排序。
  • 感谢您的回答!我如何能够转换为数组并根据值嵌套对象进行排序?

标签: javascript object lodash javascript-objects


【解决方案1】:

这会将您的对象变成可以正确排序的数组(正如@Taki 所指出的,不保证对象属性顺序)。

const object = {
  "9c8vDTruRDPi937aHMMz":{
    name: "item1",
    createdAt: {
      seconds: 1582227276, 
      nanoseconds: 68000000
    }
  },
  "rAexYu2rAz0AEnD77x5p":{
    name: "item2",
    createdAt: {
      seconds: 1582227577,
      nanoseconds: 922000000
    }
  }
};

const orderedArray = _.chain(object)
  .toPairs()
  .map(([key, ...obj]) => ({
    key,
    ...obj[0],
    createdAtSeconds: obj[0].createdAt.seconds
  }))
  .orderBy(['createdAtSeconds'], ['desc'])
  .map(({ createdAtSeconds, ...obj }) => obj)
  .value()
  
console.log(orderedArray);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2015-11-27
    • 2015-05-10
    • 1970-01-01
    相关资源
    最近更新 更多