问题
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