Search code examples
javascriptsql-order-byassociative-array

How order an associative object by value of property of contained object in javascript


For example, for this associative object:

a["id1"] = { Id: "id1", Count: 15, Other: "aaa"};
a["id2"] = { Id: "id2", Count: 5, Other: "bbb" }; 

I like to have this array:

b[0] = { Id: "id2", Count: 5, Other: "bbb" };
b[1] = { Id: "id1", Count: 15, Other: "aaa"};

Solution

  • This should do the trick:

    var b = [];
    for(x in a)
        b.push(a[x]);
    

    Order of the elements in the array won't be guaranteed, if you want that you'll have to sort the array after. Let me know if you want help with that too.