Güray Yarar
Güray Yarar

Reputation: 143

Json Array With Using Jquery UI

I have a json file like below. And I'm using jquery 1.10.1 and Jquery UI 1.10.4 version

 var jsonData =
    {
      "data": [
        {
          "image": "Content/Uploads/f1d59b7e-c93a-4419-94a6-6514d1c2384.jpg",
          "textstyles": {
            "pricecolour": "FFF",
            "checkincolour": "222"
          },
          "products": [
            {
              "product": "Product-1",
              "price": "55776"
            },
            {
              "product": "Product-2",
              "price": "24776"
            }
          ]
        }
      ]
    }

I used this code for sorting by price under the data => products

    function SortJsonData(prop, asc, jsonData) {
            jsonData = jsonData.sort(function (a, b) {
                if (asc) return (a[prop] > b[prop]);
                else return (b[prop] > a[prop]);
            });
            return jsonData;
    }

$(document).ready(function () {
        SortJsonData('price', true, jsonData);
});

I have error,

Uncaught TypeError: undefined is not a function

on the document ready method.

I need a sorting by price of product json string. How can i write this code?

Upvotes: 0

Views: 40

Answers (1)

adeneo
adeneo

Reputation: 318182

jsonData is not JSON, it's a javascript object, and objects don't have a sort() method, only arrays do, in fact objects can't be sorted as there is no guarantee of order.

If you just want to sort the products array, you can do that

jsonData.data[0].products.sort(function(a, b) {
    return a.price - b.price;
});

Upvotes: 1

Related Questions