使用 Javascript and/or Underscore.js 对嵌套对象进行排序

Sorting nested objects using Javascript and/or Underscore.js

我在使用 Javascript 或 Underscore.js 按 TearSheetTypeName 和 StartDate 对对象进行排序时遇到问题。对象看起来像这样:

{
    Components: {141: {TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"}}
                {142: {TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"}}
                {145: {TearSheetTypeName: "New Car", StartDate: "2015-01-15"}}
                {146: {TearSheetTypeName: "New Car", StartDate: "2015-01-01"}}
}

我想要的结果:

{
    Components: {146: {TearSheetTypeName: "New Car", StartDate: "2015-01-01"}}
                {145: {TearSheetTypeName: "New Car", StartDate: "2015-01-15"}}
                {141: {TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"}}
                {142: {TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"}}
}

我试过这样做:

data = _.sortBy(data, function(obj) {
           return obj.TearSheetTypeName;
       });

但它将对象更改为使用 0、1、2、3 作为对象名称,而不是 141、142、145 和 146。它也没有考虑 StartDate。

如有任何帮助,我们将不胜感激。谢谢

Components 似乎应该是一个数组。有了这个先决条件,您的对象将如下所示:

{
  Components: [
    {Id: 141, TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"},
    {Id: 142, TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"},
    {Id: 145, TearSheetTypeName: "New Car", StartDate: "2015-01-15"},
    {Id: 146, TearSheetTypeName: "New Car", StartDate: "2015-01-01"}
  ]
}

那么您甚至不需要下划线来对组件进行排序。原生Array.prototype.sort works just as well (and if you look at the underscore source, is actually used by_.sortBy().

data.sort(function(a,b){

    if(a.TearSheetTypeName > b.TearSheetTypeName){
      return 1;
    }

    if(a.TearSheetTypeName < b.TearSheetTypeName){
      return -1;
    }

    //if we got this far, the strings are the same, so sort by date
    if(new Date(a.StartDate) > new Date(b.Startdate)) {
    return 1;
    }

    if(new Date(a.StartDate) < new Date(b.Startdate)) {
    return -1;
    }

    //if we got this far, the criteria is the same
    return 0;
});

排序就地发生,所以你不需要分配它。