Я столкнулся с проблемой сортировки нескольких объектов с вложенным свойством (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"
},
]}
Объекты не могут быть отсортированы. Я предлагаю вам сопоставить данные с одним массивом, который хотел бы больше всего:
[
{
"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)
Посмотрите возможное решение, используя 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>
МОДУЛЬ
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"
}]
};
});
РЕЗУЛЬТАТ
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"}