Sorting nested objects using Javascript and/or Underscore.js

落花浮王杯 提交于 2019-12-12 01:55:15

问题


I'm having trouble sorting an object by TearSheetTypeName and StartDate using Javascript or Underscore.js. The object looks like this:

{
    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"}}
}

The result I'd like:

{
    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"}}
}

I tried doing this:

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

But it changed the object to use 0, 1, 2, 3 as object names instead of 141, 142, 145, and 146. It also doesn't take the StartDate into consideration.

Any help would be appreciated. Thanks.


回答1:


It seems like Components should be an array. With that precondition, your object would look like this:

{
  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"}
  ]
}

Then you don't even need underscore to sort Components. The native 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;
});

The sort happens in place, so you don't need to assign it.



来源:https://stackoverflow.com/questions/27810286/sorting-nested-objects-using-javascript-and-or-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!