metal_man
metal_man

Reputation: 672

Sort javascript key/value pairs inside object

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?

Upvotes: 1

Views: 7074

Answers (2)

bgusach
bgusach

Reputation: 15145

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.

Upvotes: 2

durum
durum

Reputation: 3404

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();

Upvotes: 3

Related Questions