aqq aqq - 7 months ago 48
Javascript Question

AngularJS order multiple objects array with object property

I have a multiple objects array:

{
"option_12": {
"id": "0",
"name": "6 x 330ml",
"price": "0.00"
},
"option_14": {
"id": 1,
"name": "12 x 330ml",
"price": "2.00"
},
"option_17": {
"id": 1,
"name": "15 x 330ml",
"price": "4.00"
},
"option_10": {
"id": 1,
"name": "30 x 330ml",
"price": "1.00"
}
}


I'm using the AngularJS Filter orderBy attempting to sort the objects by the price value. So in this case, option_12 should be first and option_10 should be second.

In controller:

$scope.pOptions = $filter('orderBy')($scope.pOptions, 'price');


In my view where I am populating select options using ng-options:

<select ng-model="SelectedPOption" ng-options="option.name for option in pOptions|orderBy:'price'"></select>


Neither of these have any effect. https://docs.angularjs.org/api/ng/filter/orderBy

Answer

Your markup for select is fine. It's the array that has a few problems.

  • Don't use quotes for keys in js.
  • Price should be numeric to sort correctly
  • Enclose all elements of the array using []
  • Don't call filter from js since you call it from the markup.

Example:

$scope.pOptions = [{
    id: "0",
    name: "6 x 330ml",
    price: 0.00
}, {
    id: 1,
    name: "12 x 330ml",
    price: 2.00
}, {
    id: 1,
    name: "15 x 330ml",
    price: 4.00
}, {
    id: 1,
    name: "30 x 330ml",
    price: 1.00
}];

Working example: https://plnkr.co/edit/n09iupr70zRX56kVrYK9?p=preview

EDIT: Since the data arrives like that from the backend API you can iterate the object keys/properties and use map to project the sub-objects to an array:

$scope.pOptions = Object.keys($scope.pOptions).map(function(k) {
   var obj = $scope.pOptions[k];
   obj.price = parseFloat(obj.price);
   return obj;
});