我遇到了使用嵌套属性(Price)对多个对象进行排序的问题
{
"EI":[
{
"offerid":"1S-EI-715",
"Price":"30.00"
},
{
"offerid":"1S-IB-518",
"Price":"20.00"
}
],
"IB":[
{
"offerid":"1S-IB-518",
"Price":"10.00"
},
{
"offerid":"1S-IB-518",
"Price":"40.00"
}
]}
我需要按如下方式对价格进行排序。有可能这样排序。请为此提供一些解决方案。提前致谢
{
"IB":[
{
"offerid":"1S-IB-518",
"Price":"10.00"
},
{
"offerid":"1S-IB-518",
"Price":"40.00"
}
]
"EI":[
{
"offerid":"1S-IB-518",
"Price":"20.00"
}
{
"offerid":"1S-EI-715",
"Price":"30.00"
},
]}
答案 0 :(得分:1)
无法对对象进行排序。我建议你将数据映射到更像的单个数组:
[
{
"type" : "EI",
"offerid" : "1S-EI-715",
"Price" : "30.00"
},
{
"type" : "IB",
"offerid" : "1S-IB-518",
"Price" : "40.00"
}
]
var data = {
"EI": [{
"offerid": "1S-EI-715",
"Price": "30.00"
}, {
"offerid": "1S-IB-518",
"Price": "20.00"
}],
"IB": [{
"offerid": "1S-IB-518",
"Price": "10.00"
}, {
"offerid": "1S-IB-518",
"Price": "40.00"
}]
}
var results = Object.keys(data).reduce(function(arr, key) {
var newItems = data[key].map(function(item) {
item.type = key;
return item
})
return arr.concat(newItems)
}, []).sort(function(a, b) {
return +a.Price - +b.Price
})
console.log(results)
答案 1 :(得分:0)
在视图级别使用ng-repeat
查看可能的解决方案。
显示desc
和asc
方法。
查看强>
<div id="app" ng-app="myApp" ng-controller="myCtrl">
<b>Order ASC</b>
<div ng-repeat="(name,data) in myarr">
{{name}}
<br/>
<div ng-repeat="(itemindex,itemdata) in data | orderBy:'Price'">
{{itemdata}}
</div>
</div>
<br/>
<b>Order DESC</b>
<div ng-repeat="(name,data) in myarr">
{{name}}
<br/>
<div ng-repeat="(itemindex,itemdata) in data | orderBy:'-Price'">
{{itemdata}}
</div>
</div>
</div>
<强> MODULE 强>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = {
"EI": [{
"offerid": "1S-EI-715",
"Price": "30.00"
}, {
"offerid": "1S-IB-518",
"Price": "20.00"
}],
"IB": [{
"offerid": "1S-IB-518",
"Price": "10.00"
}, {
"offerid": "1S-IB-518",
"Price": "40.00"
}]
};
});
<强> RESULT 强>
Order ASC
EI
{"offerid":"1S-IB-518","Price":"20.00"}
{"offerid":"1S-EI-715","Price":"30.00"}
IB
{"offerid":"1S-IB-518","Price":"10.00"}
{"offerid":"1S-IB-518","Price":"40.00"}
Order DESC
EI
{"offerid":"1S-EI-715","Price":"30.00"}
{"offerid":"1S-IB-518","Price":"20.00"}
IB
{"offerid":"1S-IB-518","Price":"40.00"}
{"offerid":"1S-IB-518","Price":"10.00"}