1

I have some problem with sorting items inside object. So I have something like this:

var someObject = {
    'type1': 'abc',
    'type2': 'gty',
    'type3': 'qwe',
    'type4': 'bbvdd',
    'type5': 'zxczvdf'
};

I want to sort someObject by value, and this is where I have problem. I have sorting function that should return key/value pairs sorted by value:

function SortObject(passedObject) {
    var values = [];
    var sorted_obj = {};

    for (var key in passedObject) {
        if (passedObject.hasOwnProperty(key)) {
            values.push(passedObject[key]);
        }
    }

    // sort keys
    values.sort();

    // create new object based on Sorted Keys
    jQuery.each(values, function (i, value) {
        var key = GetKey(passedObject, value);
        sorted_obj[key] = value;
    });

    return sorted_obj;
}

and function to get key:

function GetKey(someObject, value) {
    for (var key in someObject) {
        if (someObject[key] === value) {
            return key;
        }
    }
}

The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)

Does anyone know how to sort items in object?

metal_man
  • 580
  • 1
  • 9
  • 22
  • possible duplicate of [How may I sort a list alphabetically using jQuery?](http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery) – CodingIntrigue Dec 20 '13 at 08:18
  • There is no reason to sort an object. An object's properties are always displayed in alphabetical order. – nderscore Dec 20 '13 at 08:19
  • this key/value pairs are feed for drop down list. And that list should be sorted by value. I have no idea how to achieve this. – metal_man Dec 20 '13 at 08:22
  • Array sorting is a valid but yours is a object – Prasath K Dec 20 '13 at 08:25
  • I know. I thought that it is possible. As I saw on some tutorials, javascript object are not sorted - but mine is. No matter in which order, it sorts array by the key. – metal_man Dec 20 '13 at 08:50

2 Answers2

3

Plain objects don't have order at all. Arrays -that are a special types of objects- have.

The most close thing that you can have is an array with the object values sorted . Something like, for example:

 _valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
durum
  • 3,316
  • 1
  • 25
  • 30
2

You have two possibilities:

Refactor your object into an array

Something like this:

var myObj = [
    ['type1', 'abc'],
    ['type2', 'gty'],
    ...
];

Or even better, since using it somewhere would not rely on array positions but full named keys:

var myObj = [
    {name: 'type1', val:'abc'},
    {name: 'type2', val:'gty'},
    ...
];

Use your object with an auxiliar array

Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object

var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
    key = ordKeys[i]
    alert(key + " - " + myObj[key]);
}

Combination of both of them

If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.

EDIT

You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.

bgusach
  • 14,527
  • 14
  • 51
  • 68
  • I think there is also third solution - whenever I want to use sorted key/value pairs i can map this to sorted array and use it to display etc. It is not a heavy operation so I can do it dynamically, can I? – metal_man Dec 20 '13 at 09:05
  • Isn't that the second option? – bgusach Dec 20 '13 at 09:11